* fix double remove of handlers
Motivation:
Previously, it was possible that a handler was removed twice: Once by
Channel teardown and another time by a user-trigger removal that wasn't
instantaneous. This racy situation can happen in the real world. NIO
behaved wrongly in two ways:
1. we would call `handlerRemoved` twiced
2. ByteToMessageHandler would fail an assertion about the current
removal state
Modifications:
- Only call `handlerRemoved` when the handler actually gets removed.
- Fix the assertion.
Result:
fewer bugs
* Update Sources/NIO/ChannelPipeline.swift
Co-Authored-By: Cory Benfield <lukasa@apple.com>
* Fix hanging thread when shutting down an already closed EventLoopGroup
* Generate Linux tests
* Remove accidental shutdownLock.unlock
* Move dispatching of callbacks out of lock
* Use Lock.withLock instead of manual lock/unlock
* Remove superfluous lock.unlock
Motivation:
Right now NIO clients will crash in the (admittedly unlikely) event that
a HTTP server sends an unsolicited extra response on a connection. This
seems pretty unnecessary, and fairly graceless.
Modifications:
- Replace a forcible pop with an optional one.
- Added NIOHTTPDecoderError type.
Result:
Removed a crash that we definitely don't want.
Motivation:
To provide an example of the usage of the WebSocket client upgrade functionality.
To satisfy issue #465
Modifications:
Added a ‘WebSocketClient’ example with a readme and a target in the package file.
Result:
There is now a WebSocket client example to assist with the creation of a WebSocket client.
Motivation:
All ByteBuffer API that is used to parse potentially untrusted data
should be resilient against negative indices, offsets, and lenghts.
Unfortunately, ByteBuffer.viewBytes(at:length:) was not.
Modifications:
Make ByteBuffer.viewBytes(at:length:) resilient against negative values.
Result:
Fewer crashes.
Motivation:
The HTTPServerPipelineHandler is removed from pipelines in many cases,
but the most common case is over upgrade. While the handler is
removable, it doesn't make any effort to ensure that it leaves the
pipeline in a sensible state, which is pretty awkward.
In particular, there are 3 things the pipeline handler may be holding
on to that can lead to damage. The first is pipelined requests: if there
are any, they should be delivered, as the user may be deliberately
allowing pipelining.
The second thing is read() calls. The HTTPServerPipelineHandler exerts
backpressure on clients that aggressively pipeline by refusing to read
from the socket. If that happens, and then the handler is removed from
the channel, it will "forget" to restart reading from the socket on the
way out. That leaves the channel quietly in a state where no reads will
occur ever again, which is pretty uncool.
The third thing is quiescing. The HTTPServerPipelineHandler catches
quiescing events and allows them to deliver a response before closing a
connection. If that has happened when the pipeline handler is removed,
it should fall back to the behaviour as though it were not there.
Modifications:
- Added a handlerRemoved implementation to play event state that should
be replayed.
- Added a channelInactive implementation to drop data.
Result:
More graceful handler removal.
Motivation:
In NIO2 we tried to adopt the Swift convention of avoiding functions
that differ only by the word of their first label where that label is
describing their type. Sadly, we missed one.
Modifications:
- Wrote setBuffer(_:at:)
- Deprecated set(buffer:at:) in favour of the new function.
Result:
Users will get some deprecation warnings I guess.
Motivation:
Subtracting deadlines should just work, no matter if the result is
positive or negative.
Modifications:
Don't crash on earlierDeadline - laterDeadline.
Result:
- fewer crashes
- fixes https://github.com/swift-server/async-http-client/issues/71
Motivation:
Folds often involves chaining multiple futures together. It's
beneficial if you're already on the target EventLoop as it might
vastly reduce the amount of EventLoop hops.
Modifications:
Execute onto the target EventLoop before doing the folds.
Result:
Fixes#1054
Motivation:
As #1054 shows, we have some low-hanging performance fruit regarding
off-EventLoop future reduces. We should quantify those.
Modifications:
Add benchmarks to quantify the potential wins.
Result:
More benchmarks.
Motivation:
It's illegal to shut down a SelectableEventLoop because the only valid
owner is a MultiThreadedEventLoopGroup which never uses
shutdownGracefully on its EventLoops.
Modifications:
Fail shutdown attempts instead of running some random, untested code.
Result:
Fail illegal calls rather than running some dangerous code which will
lead to deadlocks further down the line.
Motivation:
Previously we thought that if we have some bytes left that belong to an
upgraded protocol, we should deliver those as an error. This is
implemented on `master` but not in any released NIO version.
However, no other handler sends errors on unclean shutdown, so it feels
wrong to do it in this one very specific case (EOF on inflight upgrade
with data for the upgraded protocol)
Modifications:
Remove the error again.
Result:
Less behaviour change to the last released NIO version.
Motivation:
Do as we documented and invoke the leftovers strategy only when the
handler is removed.
Modifications:
Don't invoke leftovers on EOF (which isn't something the user can
control).
Result:
- Fewer crashes
- should fix https://github.com/IBM-Swift/Kitura-WebSocket-NIO/issues/35
Motivation:
There is a client protocol upgrader but, unlike the server protocol upgrader, it does not have a WebSocket protocol as part of the project.
Modifications:
Made the magic WebSocket GUID public to the WebSockets project.
Added a NIOWebSocketClientUpgrader.
Added tests for the upgrader.
Updated the Linux test script files.
Result:
The project now has a WebSocket client upgrader to match the WebSocket server upgrader.
Motivation:
EventLoopFuture and EventLoopPromise are symmetric APIs and for easier
discoverability of being able to complete a promise with a future it
is helpful to have a mirror of future.cascade put onto promise.
Modifications:
- Adds ELP.completeWith(ELF)
Result:
It is now possible to complete a promise with a future,
and not only cascade a future to a promise.
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:
Previously, ByteBuffer tried to never copy the bytes when transferring
to a `Data`. For small copies that's definitely not a good choice
because it means an extra allocation.
Modifications:
- introduce `ByteTransferStrategy` so the user can choose
- make a heuristic: copy is less than 256kB, try not to copy above
Result:
More sensible defaults.
Motivation:
We accidentally removed NIOFileHandle(path:) when we added some
arguments with default values to it. This doesn't normally break source,
but in some weird edge cases it can, and it's bad form to remove it.
Modifications:
- Replace the missing function
Result:
Fewer highly unlikely source breakages.
Motivation:
Darwin does sometimes hand us back an (as of the docs) illegal error
code of EINVAL. So far, NIO has done the non-sensical thing of closing
the server socket as a result.
Modifications:
Just close the accepted socket, leave the server socket open, and fire
the error through the pipeline.
Result:
- fixes#1030
- better behaviour
Motivation:
Previously, we would just `F_SETFL, O_NONBLOCK` which would erase all
possibly pre-existing flags which isn't great.
Modifications:
First get the existing flags and then do `F_SETFL, existingFlags |
O_NONBLOCK`.
Result:
Possibly helps with #1030, definitely better style.
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
* Reorder ‘channel active’ calls to the same order as `_ChannelInboundHandler` and their likely chronological order.
Motivation:
When first viewing the example classes, coming to the ‘read’ method first, leaves the subject unclear as to what the method is ‘reading’.
It is preferable to view something being sent first, and then to view the reading of the response.
It also matches the call order against the protocol making it a little easier for those unfamiliar with the protocol to see which methods have been implemented.
Modifications:
Moved channel active calls to be top of the class.
Despite the diff there are no actual code modifications.
UDP Client changed to indent using spaces to match rest of project. Incidental change.
Result:
The examples are slighter clearer to read, particularly for newcomers to swift-no as the calls are in a logical chronological order.
* Fix an error in the upgrader and its tests which checked the connection header incorrectly.
Motivation:
To correct the logic in the upgrader. Previously it checked if the upgraders required headers include the connection header. Now it checks that the connection header value was present as a separate header in the incoming request.
To prepare the class naming for the presence of a client upgrader.
Modifications:
Slight change in server upgrader handler logic with accompanying tests.
Renamed upgrader and test files to include the word ‘server’.
Ran the linux test script.
Result:
The server upgrader now checks for the presence of the connection header value as a header of its own.
* Rename WebSocketServer upgrader to make the naming clearer and make way for a client version.
Motivation:
To make the web socket upgrader naming clearer, particularly once we add a client version.
Modifications:
Rename WebSocketUpgrader too WebSocketServerUpgrader.
Result:
Improved clarity of naming on the web socket upgrader.
* Adds correct naming conventions to NIOWebSocketServerUpgrader. Sets back an incorrect fix (non-fix).
* Move deprecation for NIOWebSocketServerUpgrader typealias out of API shims file.
* Makes HTTPEncoder removable.
Adds a client upgrade handler with tests.
Adds the ability to use a client upgrader to the client setup.
Initial linux file update.
* Allow assertContains to be accessed publicly, so that it can be used in the client side tests.
* Update tests to remove server upgrader from client tests.
Change client tests to use Embedded channel.
Update HTTPUpgradeConfiguration class name to be NIOHTTPServerUpgradeConfiguration
Few other small stylistic changes.
* Removed awaiting upgrader state.
Removed future from handle upgrade call as is synchronous.
Removed protocol iterator from handle upgrade call as is not required by the client.
* Ensure that the client handler calls for the HTTPPipeline are backwards compatible.
Ensure that incoming promises to the handler write call are completed.
Neaten the upgrade header formation to remove looping.
Improve the correctness of the upgrade error throwing.
* Update scripts to match new unit tests.
* Change the documentation for HTTPServerPipeline to remove nil options which have now been removed.
* Restore an incorrectly added server pipeline comment change and make it to the client pipeline instead.
* Raise the allocation limits in the docker images to allow the tests to pass.
Motivation:
I noticed some closures were referred to by the wrong name in the
documentation.
Modifications:
Updated the documentation to use the correct names.
Result:
More correct documentation.
Motivation:
When testing programs that check flow control state, it's useful to be
able to control the results of that check. However, right now it's not
possible to set the flow control state of an EmbeddedChannel: it's just
always true. That's not super helpful.
Modifications:
Make EmbeddedChannel.isWritable a stored property that can be changed.
Result:
Better testing.
Motivation:
When using CircularBuffer as a storage object it would be helpful to be
able to write directly into the underlying storage. As the _modify
accessor is currently underscored and not really safe for us to use, the
next best option is to write a function that takes advantage of the
_modify access on the underlying Array. This patch provides that
function.
Modifications:
- Implemented CircularBuffer.modify(_:_:)
Result:
It'll be possible to use a fast function to access the underlying Array
storage.
Motivation:
When receiving the ChannelShouldQuiesceEvent event, the AcceptHandler
correctly closes the ServerChannel. However, if that fails, it swallows
the error which is incorrect.
Modifications:
Don't swallow the error, send it through the pipeline.
Result:
More correct.
Motivation:
We left a doc comment on EventLoopFuture.map that caused confusion by
misleadingly claiming that it could handle throwing functions. The
operation that handles throwing functions is flatMapThrowing.
Modifications:
- Removed the misleading comment and pointed users to flatMapThrowing
instead.
Result:
Less user confusion.
Motivation:
In #957 we accidentally broke the API just a little bit. We turned the
`ByteToMessageHandler.init` from
public init(_ decoder: Decoder)
into
public init(_ decoder: Decoder, maximumBufferSize: Int? = nil)
This looks totally benign and in almost all cases because of the default
argument, you wouldn't notice the API breakage. However, it's possible
to write code that works in NIO 2.0.0 but breaks in NIO 2.1.0. For
example
let g: (Dummy) -> ByteToMessageHandler<Dummy> = ByteToMessageHandler<Dummy>.init
let h: (Dummy) -> ByteToMessageHandler<Dummy> = ByteToMessageHandler<Dummy>.init(_:)
Modifications:
According to SemVer, this releases a patch that unbreaks the public API.
Result:
No API breakages (checked with `swift-api-digester` which also found the
breakage in the first place).
Motivation:
In many unit tests, it's important to count the events. So far we have
many many ad-hoc handlers to do so but having one that counts all events
would be handy.
Modifications:
Add `EventCounterHandler` to count all events travelling the
`ChannelPipeline`.
Result:
Easier unit testing
* Allow adding a sequence of headers to HTTPHeaders
Motivation:
When combining two collections of headers, adding each pair one-by-one
using add(name:value:) can cause multiple unnecessary reallocations of
the underlying array.
Modifications:
Provide two additional add methods to HTTPHeaders: one to add a sequence
of name/value pairs and another to add the headers from another
HTTPHeaders, both of which use `append(contentsOf:)` on the underlying
array to avoid additional reallocations.
Result:
Fewer reallocations when adding multiple headers.
* Fix incorrect documentation, make add<S: Sequence>(contentsOf:) @inlineable
* Reserve capacity and add sequentially instead of using append(contentsOf:)
* Add tests and missing @usableFromInline
Add an `always` method on EventLoopFuture
Motivation:
https://github.com/apple/swift-nio/issues/665
Modifications:
* Add `always` in EventLoopFuture.swift
* Add tests
Result:
NIO Users will be able to use `.always` to, well, always run an action
wether the future succeed or not.
Motivation:
When writing B2MDs, there are a couple of scenarios that always need to
be tested: firehose feeding, drip feeding, many messages, ...
It's tedious writing those tests over and over again for every B2MD.
Modifications:
- Add a simple B2MD verifier that users can use in unit tests.
- Add a new, public `NIOTestUtils` module which contains utilities
mostly useful for testing. Crucially however, it does not depend on
`XCTest` so it can be used it all targets.
Result:
Hopefully fewer bugs in B2MDs.
Motivation:
New public NIO types must be nested in existing ones or `NIO` prefixed.
This wasn't the case for ByteToMessageDecoderPayloadTooLargeError
Modifications:
nest PayloadTooLargeError into ByteToMessageDecoderError
Result:
we stick to our rules.
Motivation:
With HTTP/1.0 and EOF framing it's possible to have a HTTP response that
doesn't have any headers. HTTPDecoder unfortunately fell flat on its
face and crashed the program if that happened.
Modifications:
- don't expect headers on responses
- add tests for that
- rename the state machine cases to reflect a request and response
parsing
Result:
fewer crashes.
Motivation:
Due to https://bugs.swift.org/browse/SR-10614, assigning an array containing a tuple type
to a variable that expects an array containing a different-but-compatible tuple type will cause
an allocation and copy of that array storage.
In some cases this is necessary, but we were doing it in the HTTPHeaders constructors, which meant
that the swift-nio-http2 code was hitting a hilariously over the top number of allocations.
Modifications:
- Change the internal storage type of HTTPHeaders to match the public constructor.
Result:
Fewer allocations when constructing HTTPHeaders
Motivation:
While CircularBuffer has an inlinable implementation to improve performance, MarkedCircularBuffer
never got enhanced to have it. This harms performance in many core NIO libraries which heavily use
MCB, forcing heap allocations on almost all MCB operations.
Modifications:
- Make basically everything on MarkedCircularBuffer inlinable.
Result:
Faster code.
Motivation:
The new file RW opening facilities didn't have any tests and it didn't
let you specify arbitrary POSIX flags.
Modifications:
- Add tests.
- Let users specify both POSIX flags & mode.
Result:
Better code quality.
Motivation:
To make the web socket upgrader naming clearer, particularly once we add a client version.
Modifications:
Rename WebSocketUpgrader too WebSocketServerUpgrader.
Result:
Improved clarity of naming on the web socket upgrader.
Motivation:
Structures that users can't create don't give them much value.
Modifications:
- Make the initializer public.
- Remove that godforsaken @testable import.
Result:
ChannelOptions.Storage sparks joy.
Motivation:
https://github.com/apple/swift-nio/issues/966
Modifications:
- Add a `handler(type:)` method on ChannelPipeline
- Add a test in ChannelPipelineTest
Result:
Provides a nicer way to get a typed handler directly from the pipeline
Closes#966
Motivation:
https://github.com/apple/swift-nio/issues/701
Modifications:
* Add `init(rawValue:)`
* Add `rawValue`
* Add tests in HTTPTypesTest.swift
Result:
Users no longer have to write their own conversion methods.
Motivation:
Because of #600, many users will start leaking Channels because they
don't close on error.
Modifications:
* Add ChannelHandlerError
* Add ChannelHandlerErrorTest
Result:
User will have access to an handler to use to automatically close
the channel in case of unhandled errors
Motivation:
The HTTPDecoder is a complex object that has very careful state management goals. One source of this
complexity is that it is fed a stream of bytes with arbitrary chunk sizes, but needs to produce a
collection of objects that are contiguous in memory. For example, each header field name and value
must be turned into a String, which requires a contiguous sequence of bytes to do.
As a result, it is quite common to have a situation where the HTTPDecoder has only *part* of an
object that must be emitted atomically. In this situation, the HTTPDecoder would like to instruct
its ByteToMessageHandler to keep hold of the bytes that form the beginning of that object. To avoid
asking http_parser to parse those bytes twice, the HTTPDecoder uses a value called httpParserOffset
to keep track.
As an example, consider what would happen if the "Connection: keep-alive\r\n" header field was delivered
in two chunks: first "Connection: keep-al", and then "ive\r\n". The header field name can be emitted in
its entirety, but the partial field value must be preserved. To achieve this, the HTTPDecoder will store
an offset internally to keep track of which bytes have been parsed. In this case, the offset will be set
to 7: the number of bytes in "keep-al". It will then tell the rest of the code that only 12 bytes of the
original 19 byte message were consumed, causing the ByteToMessageHandler to preserve those 7 bytes.
However, when the next chunk is received, the ByteToMessageHandler will *replay* those bytes to
HTTPDecoder. To avoid parsing them a second time, HTTPDecoder keeps track of how many bytes it is
expecting to see replayed. This is the value in httpParserOffset.
Due to a logic error in the HTTPDecoder, the httpParserOffset field was never returned to zero.
This field would be modified whenever a partial field was received, but would never be returned
to zero when a complete message was parsed. This would cause the HTTPDecoder to unnecessarily keep
hold of extra bytes in the ByteToMessageHandler even when they were no longer needed. In some cases
the number could get smaller, such as when a new partial field was received, but it could never drop
to zero even when a complete HTTP message was receivedincremented.
Happily, due to the rest of the HTTPDecoder logic this never produced an invalid message: while
ByteToMessageHandler was repeatedly producing extra bytes, it never actually passed them to http_parser
again, or caused any other issue. The only situation in which a problem would occur is if the HTTPDecoder
had a RemoveAfterUpgradeStrategy other than .dropBytes. In that circumstance, decodeLast would not
consume any extra bytes, but those bytes would have remained in the buffer passed to decodeLast, which
would then incorrectly *forward them on*. This is the only circumstance in which this error manifested,
and in most applications it led to surprising and irregular crashes on connection teardown. In all
other applications the only effect was unnecessarily preserving a few tens of extra bytes on
some connections, until receiving EOF caused us to drop all that memory anyway.
Modifications:
- Return httpParserOffset to 0 when a full message has been delivered.
Result:
Fewer weird crashes.
* Add ability to open a file for writing
Motivation:
Users can use NonBlockingFileIO for reading files, but if one wants to
write a file, there is no way to achieve that, apart from opening file
manually. I think having to inits to open files for reading and writing
would be convinient.
Modifications:
Allow to open files for writing.
Result:
Users can now open files for writing and reading in the same way.
Motivation:
CircularBuffer.Index was asserting that its size is the same as a word.
Whilst that's true on 64-bit architectures, the assert itself is bogus
and a left-over from development.
Modifications:
Remove bogus assert.
Result:
Better 32-bit support.
* optional max payload size for ByteToMessageDecoder
Motivation:
ByteToMessageDecoder aggregate data in memory as part of their normal operation. the ability to limit how much they aggregate is critical in many real-life applications
Modifications:
* add optional maximumBufferSize argument to ByteToMessageDecoder initializer
* test for buffer size when maximumBufferSize is set and throw ByteToMessageDecoderError.payloadTooLarge error
Result:
users can limit how much memory ByteToMessageDecoder takes and handle the exception on their end
Motivation:
The file-io implementation in the example HTTP1 server just crashed on
empty file ;).
Modifications:
- fix the crash
- add integration test
Result:
fewer crashes