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:
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:
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:
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!
Motivation:
The http handler was not removed after the websocket upgrade and so a crash could happen as the handler assumes it received HTTP data.
Modification:
Remove httpHandler from pipeline
Result:
Fix receiving message from websocket client
Motivation:
The BlockingIOThreadPool were very sparse which is improved here.
Modifications:
The existing docs didn't really help much if you didn't already know why
you'd need an extra thread pool for blocking work.
Result:
docs more clear on when to use BlockingIOThreadPool
Motivation:
In the NonBlockingFileIO, the docs contain links but the scheme was
missing so the links didn't work.
Note: Both URLs don't work with https:// so I had to use http://,
sorry...
Modifications:
added a scheme to the URLs so they actually work
Result:
dead links in NonBlockingFileIO fixed
Motivation:
In Darwin it is possible for readEOF to be received before writable,
if we race connection teardown with registering for writable. See
https://github.com/apple/swift-nio/issues/452 for a more in-depth
explanation.
Modifications:
Widened the assertion.
Result:
People's code won't go bang.
Motivation:
Sometimes it would be handy to have ByteBuffers conform to a
`Collection` where `Element == UInt8`. ByteBuffer however has multiple
modes how to operate so it would be wrong to have say the readable bytes
be the ByteBuffer's collection.
Therefore it would be nice to have a view into a `ByteBuffer` which is a
`Collection where Element == UInt8`. This introduces these.
Modifications:
- add `ByteBufferView`
- add `ByteBuffer.readableBytesView`
- add `ByteBuffer.viewBytes(range: ...)`
Result:
- easier to work with `ByteBuffer`s in the Swift ecosystem.
Motivation:
ByteBuffer._ensureAvailableCapacity is quite complicated and the code
can be simplified by re-using existing code.
Modifications:
reuse more existing code
Result:
ByteBuffer code easier to understand
Motivation:
_UInt24 and _UInt56 didn't have a CustomStringConvertible conformance
which this patch is adding.
Modifications:
add CustomStringConvertible instances.
Result:
easier to debug stuff
Motivation:
We should be consistent with naming and also choose descriptive names.
Modifications:
- Deprecate old init method that uses numThreads
- Add new init with numberOfThreads param name
- Everywhere use the new init
Result:
More consistent and descriptive naming. Fixes https://github.com/apple/swift-nio/issues/432.
Motivation:
This is done because when using Xcode and option + Click on a function you get a help overview inline to see more information and the messaging was incorrect. This helps developers in the future who want to rely on docs via Xcode.
Modification:
Correct the docs
Result:
More correct docs.
Motivation:
d53ee6dafc introduced a new constructor to HTTPRequestDecoder which allows to change the behaviour of handling left over bytes when an upgrade was detected and the decoder was removed. This was done as an internal init block as we wanted to to do as part of a patch release.
Modifications:
Change internal to public init
Result:
More flexible configuration possible.
Motivation:
When we don't care about the result of an operation, we shouldn't provide
a promise.
While I'm here I also removed an unnecessary close() call in the
AcceptHandler: the close() would be called again almost immediately.
Modifications:
Removed a close() call.
Set `promise: nil` on a pair of close() calls.
Result:
Fewer promise allocations.
Motivation:
398b950eee introduced a change which forwarded bytes that were buffered in HTTPDecoder after it was removed when an upgrade was detected. This may be risky if we dont know that the pipeline can handle it.
Modifications:
- Add new initializer that allow us to configure if we should forward bytes or not.
- Automatically use this if we know that we added an upgrader
- Add unit tests.
Result:
Less risky implementation.
Motivation:
The Darwin gathering datagram writes shim incorrectly placed the
"bytes written" amount into the first slot in the array for every write.
This had the effect of incorrectly accounting for the amount of bytes
written for literally every element of a vector write. Not good.
Modifications:
Correctly account for each vector write element.
Result:
Lower risk of preconditions in incorrect situations, better accounting
of written bytes.
Motivation:
We need to ensure we correctly guard against re-entrancy for all cases. Also we did not correctly ensure we forward pending data after removal which could lead to missing data after upgrades.
Modifications:
- pause the parser when we need to callout to the pipeline and so ensure we never fire events throught the pipeline while in callbacks of http_parser
- correctly forward any pending bytes if an upgrade happened when the decoder is removed
- Ensure HTTPUpgradeHandler only remove decoder after the full request is received
- Add testcase provided by @weissi
Result:
Correctly handle upgrades and pending data. Fixes https://github.com/apple/swift-nio/issues/422.
Motivation:
Previously we were not running the (child/server)channelInitializers on the
event loop associated to the `Channel` we're initialising. Almost all
operations in there are pipeline modifications which are thread safe so
it presumably wasn't a massive correctness issue. However it's very
expensive to hop threads that often and it is also very unexpected. This
addresses this issue.
Modifications:
made all (child/server)channelInitializers run on the event loop that is
associated to their `Channel`
Result:
- more correctness
- less unexpected behaviour
Motivation:
If registration of a Channel fails we need to close that Channel.
Previously we'd just drop it on the floor which triggers an assertion
that an open channel got leaked.
Modifications:
In cases where the Channel registration fails, we need to close that
channel.
Result:
- No crashes if registration fails.
- fixes#417
Motivation:
A long time ago, `ChannelPipeline.channel` was public and needed to be
thread-safe. That meant we could never mutate `ChannelPipeline.channel`.
Instead we stored it as an unowned reference that we only read when the
`Channel` was still alive.
It was the right call making `ChannelPipeline.channel` internal but we
forgot to then remove the `unowned` reference from `ChannelPipeline` to
`Channel`. This patch makes this reference strong but nils it out
whenever the `ChannelPipeline` is destroyed. That makes everything
easier because there is no danger anymore that the `Channel` gets
deallocated when the `ChannelPipeline` is still alive.
After destroying the `ChannelPipeline` we will still hand out a
`DeadChannel` if you call `ctx.channel` (as it's a non-optional
requirement).
This comes with an unfortunate drawback: Now if you just leak an open
Channel (which you shouldn't be able to when using the Bootstraps) we
can no longer detect that as the Channel and the ChannelPipeline will
have a retain cycle. Unfortunately I don't think there's a good way to
safely assert that.
Modifications:
- made `ChannelPipeline` hold a strong reference to `Channel` until the
`ChannelPipeline` is destroyed
Result:
- don't crash if the user only retains the ChannelPipeline but not the
Channel
Motivation:
We should explain why this typealias
public typealias RangeType<Bound> = CountableRange<Bound> where Bound: Strideable, Bound.Stride: SignedInteger
isn't just
public typealias RangeType = CountableRange
and that's because SR-6963.
Modifications:
added a comment explaining why
Result:
code easier to read
Motivation:
Because EmbeddedChannel used to treat all writes as flushed the test
that tested that we do send out the WebSockets connection close frame
didn't actually test the right thing. Now that EmbeddedChannel behaves
more realisticly, this test actually fails.
This fixes the bug and the test that tests that a WebSockets connection
is successfully torn down after an error occured.
Modifications:
- use `writeAndFlush` to send out the connection close frame.
Result:
WebSockets connection actually gets closed on error.
Motivation:
EmbeddedChannel just treated all `write`s as flushed. That's not a good
idea as all real channels obviously only actually write the bytes when
flushed. This changes that behaviour for `EmbeddedChannel`.
Modifications:
- make `write` only write to a buffer
- make `flush` then actually pretend to write the bytes
Result:
- EmbeddedChannel behaves more realisticly
Motivation:
SR-6963 is currently blocking builds with Swift 4.2 pre-releases, we
should work around it.
Modifications:
work around SR-6963.
Result:
builds with 4.2 pre-release
Motivation:
If ChannelPipeline.removeHandlers is internal it is extremely difficult
to implement a correct ChannelCore. For that reason, we should make it
available as an extension on ChannelCore.
This is a minor layering violation, but that's ok: ChannelCore and
Channel are not actually intended to be separate objects in most cases,
they are just separate for code clarity reasons.
Modifications:
Add ChannelCore.removeHandlers as a public method.
Result:
Easier to implement ChannelCore.
Motivation:
In certain cases it's useful to quiesce a channel instead of just
closing them immediately for example when receiving a signal.
This lays the groundwork by introducing the
`ChannelShouldQuiesceUserEvent` user event that when received can be
interpreted by a ChannelHandler in a protocol & application specific
way. Some protocols support tear down and that would be a good place to
initiate the tear down.
Modifications:
- introduce `ChannelShouldQuiesceUserEvent`
- handle `ChannelShouldQuiesceUserEvent` in the `AcceptHandler` with
closing the server socket
- handle `ChannelShouldQuiesceUserEvent` in the
`HTTPServerPipelineHandler` by only handling a already in-flight
request and then no longer accepting input
- added `CircularBuffer.removeAll` (& tests)
- added tests for `nextPowerOf2()`
Result:
- handlers can now support quiescing
Motivation:
Minus [SR-7578](https://bugs.swift.org/browse/SR-7578) which will be
fixed soon, we should then compile warning-free in `-swift-version 4`
mode which is good.
However, we should also be as warning-free as possible in
`-swift-version 4.2`. This is not entirely possible because of
`@_inlineable` vs `@inlinable` but we can address the other warnings.
Modifications:
- make `CountableRange` vs `Range` (which used to be separate types but
are now the same) work warning-free Swift 4.[01] and Swift 4.2
Result:
Fewer warnings.
Motivation:
We can check if a HTTP message is using keep alive without any allocation.
Modifications:
Directly act on the internal storage of HTTPHeaders to find out if keep alive is used or not.
Result:
Less allocations
Motivation:
To detect if keepalive is used we need to search the headers (if HTTP/1.1 is used). This may be expensive depending how many headers are present. http_parser itself detects already if keep alive should be used and so we can re-use this as long as the user did not modify the headers.
Modifications:
Reuse keepalive parsed by http_parser as long as the headers were not modified.
Result:
Less overhead as long as the headers are not modified.
Motivation:
NIO wants to be a highly performant library and therefore we need
performance tests.
Modifications:
Add a couple of performance tests.
Result:
Easier to talk about perf improvements/regressions if we use similar
benchmarks.
Explicitly define constants through Posix and import errno.h
Motivation:
We implicitly depend on errno's ENOENT in Linux.swift, but don't explicitly import errno.h.
Similarly, in some cases the compiler can be confused as to where SHUT_* come from, so make them an exported value from Posix instead.
Result:
Compiles successfully on Linux and Darwin.
Motivation:
When the ByteToMessageDecoder re-entranced in its decode(...) / decodeLast(...) methods it could be possible that the ordering of processing and so the seen bytes are mixed.
Modifications:
- Refresh the buffer (and take a slice) on each loop iteration and update the cumulationBuffers indicies.
Result:
More robust code.