Motivation:
It's hard to keep track of all the pieces that do multiplexing. When
making some changes I found myself writing down what each piece did and
how they fit together. I think this is generally useful information for
anyone maintaining the library.
Modifications:
- Add a DocC article about the different multiplexing approaches that's
aimed at _maintainers_ of NIOHTTP2.
Result:
Easier to learn about how multiplexing is done
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
NIO has a 'ChannelShouldQuiesceEvent' which channels can listen for in
order to know when they should quiesce. This is typically used to
initiate a graceful shutdown of an HTTP/2 server. However, child
channels aren't notified of this event so HTTP/2 servers must keep track
of streams separately in order to notify them when the server is
quiescing.
Modifications:
- Propagate the `ChannelShouldQuiesceEvent` to child channels
Result:
Child channels can watch for `ChannelShouldQuiesceEvent`s
Motivation:
A potential race exists between a server sending a GOAWAY frame and a
client opening a new stream (i.e., sending a HEADERS frame before
receiving an already sent GOAWAY frame). If there are no open streams
when the server sends the GOAWAY frame, the connection state on the
server transitions to being fully quiesced, which throws a connection
error on receipt of a HEADERS frame.
Modifications:
- Adjust the connection state machine on the server to throw a stream
error (instead of a connection error), and consequently, send a
RST_STREAM frame to the client.
Result:
This condition will be treated as a stream-level error instead.
Motivation:
When the connection is fully quiesced, an endpoint responds with a
connection error when it receives or tries to respond to a PING frame.
This behaviour is unnecessary.
Modifications:
- Adjust `HTTP2ConnectionStateMachine` to successfully receive and send
PING frames even when the connection is fully quiesced.
Result:
When the connection is fully quiesced, an endpoint will treat receipt
and sending of a PING frame as it would when the connection is active.
Motivation:
Currently, HEADERS frames are ignored by the client on a client-initiated stream after the client sends a GOAWAY.
As per [Section 6.8 (GOAWAY) in RFC 9113](https://httpwg.org/specs/rfc9113#GOAWAY):
_"Once the GOAWAY is sent, the sender will ignore frames sent on streams **initiated by the receiver** if the stream has an identifier higher than the included last stream identifier."_
In this case, the client (sender) should **not** ignore the HEADERS frame as the stream is initiated by the _client_, not the receiver.
Modifications:
Fixed the condition in the `receiveHeaders` function (given `LocallyQuiescingState`) in `ReceivingHeadersState.swift` to work for _both_ the client and server roles -- before this change, the condition is only correct when `self.role == ConnectionRole.server`
Result:
HEADERS frames are not ignored by the client on a client-initiated stream when locally quiescing.
Motivation:
The HTTP2StreamChannel stores two atomic booleans for whether the
channel is active and writable. These are only accessed externally and
access is relatively infrequent. Each atomic requires an allocation,
instead we can just protect each with a single lock.
Modifications:
- Combine the two atomics into a single 'flags' struct protected by a
locked value box
Result:
Fewer allocations
* Make HEADERS frame payload non-indirect
Motivation:
In previous patches we shrank the size of HTTP2Frame by
making various data types indirect in the frame payload.
This included HEADERS, which is unfortunte as HEADERS frames
are quite common.
This patch changes the layout of the HEADERS frame to remove the
indirect case.
Modifications:
- Move END_STREAM into an OptionSet.
- Turn the two optional bits into flags in the aforementioned
OptionSet
- Replace the properties with computed properties.
- Remove the indirect case
Result:
HEADERS frames are cheaper.
* Update alloc limits
---------
Co-authored-by: George Barnett <gbarnett@apple.com>
Co-authored-by: Gustavo Cairo <gus.cairo@apple.com>
## Motivation
When creating stream channels on the `InlineStreamMultiplexer`, we are currently performing a `flatSubmit` on two different codepaths. This allocates two ELFs: one on `submit`, and one on `flatMap`. This is unnecessary, as we could do with just one allocation.
## Modifications
Create a single ELP and call `execute` on the EL instead of using `flatSubmit`.
## Result
Fewer allocations
Allocation tests currently use a func that takes a promise to create the stream multiplexer.
However, we also provide a different API that doesn't require a promise and instead returns an `EventLoopFuture<Channel>`.
We don't currently have allocation tests for the latter, so this PR duplicates the current H2 tests but uses the non-promise API to create the multiplexer.
I also had to add a new method on the old H2 multiplexer to conform to a test protocol.
Motivation:
When the stream channel has closed it drops all of its pending reads. It
does this by calling 'removeAll()' on its CircularBuffer. The buffers
underlying storage is emptied and then a `nil` is appended (internally
CircularBuffer is never empty) which triggers an allocation.
Modifications:
- Remove all but keep capacity
Result:
Fewer allocations
Motivation:
Existential errors are unconditionally boxed. We typically create and
use errors to fail promises when performing cleanup work. One example
of this is failing pending writes when a stream channel is closed,
however this is done unconditionally which means every stream channel
incurs an allocation when it closes.
Modifications:
- Statically create some existential errors ahead of time
Result:
Fewer allocations
* Reject long sequences of CONTINUATION frames
Motivation:
Long sequences of CONTINUATION frames can be used to mount attacks by attempting to get a remote peer to consume large amounts of memory.
Modifications:
- Add a limit to the number of sequential CONTINUATION frames that can be received. This limit is configurable by users at the NIOHTTP2Handler level and has a default value of 5. When this limit is exceeded, the recipient responds with a GOAWAY frame and an "Enhance Your Calm" error of a newly created type `ExcessiveContinuationFrames`.
Result:
Long sequences of CONTINUATION frames are now rejected by the recipient.
* Refactor implementation
* Minor adjustments
* Implement adjustments
- Refactor implementation
- Revert unnecessary diffs
* Implement adjustments
- Change `public let maximumSequentialContinuationFrames` to `public var`.
- Refactor implementation.
* Implement minor adjustments
* Store the default `maximumSequentialContinuationFrames` in a `private static let`
---------
Co-authored-by: George Barnett <gbarnett@apple.com>
Motivation:
When accumulating sequences of CONTINUATION frames, each frame is parsed
from a buffer. These bytes are read when the CONTINUATION frame is
parsed, but if more CONTINUATION frames follow then the buffer isn't
reset. This means that long sequences of CONTINUATION frames can result
in a larger than necessary buffer where most of the contents have
already been read.
Modifications:
- Discard the bytes of the accumulation buffer when transitioning back
to AccumulatingHeaderBlockFragmentsParserState if more than half of
the buffer has been read.
Result:
Lower memory footprint when parsing sequences of CONTINUATION frames.
Motivation:
`configureAsyncHTTP2Pipeline` doesn't allow a stream delegate to be
specified. As the async pipeline uses the "inline" stream multiplexer
there's no way to account for streams within the connection channel.
Modifications:
- Add a sync and async variants of `configureAsyncHTTP2Pipeline` which
accepts an optional stream delegate
- Rewrite the existing helpers in terms of the new one
Result:
Users can configure an async http pipeline with a stream delegate.
Motivation:
CoWs appear when switching over the current state of the parser and holding it while also modifying it - inside `processNExtState()`. Following `append(bytes: ByteBuffer)`'s pattern, we should use a function that sets the state to an intermediary one with no associated data, before making the transformations.
Modifications:
- created the `avoidParserCoW()` helper function for the throwing functions
- used it in the switch cases inside `processNextState()`
Result:
CoW will be avoided when changing the state of the HTTP2FrameDecoder when decoding, so we won't have unnecessary heap allocations.
Motivation:
If a task iterating over inbound streams using the new async API is
cancelled then it can lead to the process crashing as we hit a
precondition which guards against yielding to a terminated
NIOHTTP2AsyncSequence.
Modifications:
Remove the precondition.
Result:
The code no longer crashes, instead it silently drops the yielded value.
Doing more than this such as closing the connection requires rethinking
more of the API.
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
To address warnings revealed with
`.enableExperimentalFeature("StrictConcurrency=complete"),` in Swift 5.8
Modifications:
* Numerous protections of state in tests
* Make the multiplexer instances explicitly loop bound
* Update channel initializers to be marked as Sendable
* Mark error backing storage types as unchecked sendable
Result:
Better thread safety
* Mark generic async methods inlinable
Motivation:
Mark generic async methods inlinable where possible to improve performance.
Modifications:
Multiple methods marked `@inlinable`
Result:
Performance increase
We previously developed an async API for NIO HTTP/2 which was guarded under SPI. Now that the swift-nio async API is released we can reintroduce this code promoted to SPI.
This change introduces:
* `AsyncStreamMultiplexer` - an async variant of the HTTP/2 stream multiplexer which can be used to create outbound streams and provide access to an async sequence (`NIOHTTP2AsyncSequence`) of inbound streams
* New pipeline configuration functions (e.g. `configureAsyncHTTP2Pipeline`) to support the new async mode
* Bump minimum Swift version to 5.7
Motivation:
Now that Swift 5.9 is GM we should update the supported versions and
remove 5.6
Modifications:
* Update `Package.swift`
* Remove `#if swift(>=5.7)` guards
* Delete the 5.6 docker compose file and make a 5.10 one
* Update 5.10 alloc limits
* Update docs
Result:
Remove support for Swift 5.6, add 5.10
Motivation:
The type inference system isn't able to work out the default clock type
in the DOSHeuristics init on Swift 5.6 so this change makes it more explicit
Modifications:
Add more explicit inits
Result:
The code should build on 5.6 and later
* Limit rate of permitted RST frames
Motivation:
Large number of stream reset frames may be used as a DoS (Denial of
Service) vector in an attempt to overload the CPU of the handling server.
Modifications:
Introduce an additional DoS heuristic which evaluates the rate of
incoming stream reset frames. If the rate exceeds that which is
permitted then the connection is closed and a `GOAWAY` issued.
The allowed rate is configurable but defaults to 200 resets within 30
seconds. This should be acceptable for most applications.
Result:
Excessive reset frames result in the connection being closed.
* review comments
* further review comments
* add integration test
Motivation:
Remove dependency on SPI so that we can cut a release without
introducing dependency on code subject to change.
Modifications:
Remove all code which introduces a dependency on the NIOAsyncChannel SPI
Result:
Code inside SPI is removed
Motivation:
When adding in the SPI methods for exposing async sequences of HTTP/2
streams we moved the stream initialization to a subtly different
location so that it was easier to exfiltrate the outputs of those
initialization functions (such as protocol negotiation outputs).
In some cases this broke ordering expectations.
Modifications:
Yield the (optionally wrapped) channels as initializer outputs to the async stream
Result:
Changes only exist within SPI. Async inbound stream channel
initialization now matches previous behavior.
Motivation:
A recent change allowed stream creation to run immediately if the caller
was on the correct event loop. Normally that's fine, however, it opens
up a code path where streams can become activated twice which leads to a
crash.
Modifications:
- Delay stream creation until the next loop tick
- Add a loop tick to tests which now require it
Result:
Avoid re-entrantly activating streams twice.
* Update to latest NIO with updated protocol negotiation API
Signed-off-by: Si Beaumont <beaumont@apple.com>
* fixup: Also replace deprecated get().waitForFinalResult()
Signed-off-by: Si Beaumont <beaumont@apple.com>
---------
Signed-off-by: Si Beaumont <beaumont@apple.com>
Motivation:
Make sure the order of `HTTP2Frame`s that are fired through the pipeline of a `HTTP2StreamChannel` by `HTTP2CommonInboundStreamMultiplexer` is correct when a `read()` call on the parent channel synchronously causes further frames to be processed.
Modifications:
Reorder calls in `HTTP2CommonInboundStreamMultiplexer.receivedFrame(frame:context:multiplexer)` so that initial header frame is buffered and processed first.
Result:
Resolves#410 and makes newly added test case `HTTP2StreamMultiplexerTests.testMultiplexerFiresInitialFramesInCorrectOrder()` pass.
# Motivation
In my latest PR in NIO, I removed a bunch of API from the bootstrap methods to make the API easier to digest and reduce a number of duplicated code issues.
# Modification
This PR adopts the latest NIO changes and adapts the APIs in H2. More specifically, it removes the `NIOAsyncChannel` convenience methods and makes sure that everything aligns nicely with the proposes bootstrap APIs.
# Result
We now have the APIs in place to bootstrap a protocol negotiated H1/H2 server.
Motivation:
This continues the work to expose functionality which allows users to interact
with HTTP/2 connections via async abstractions and using structured
concurrency.
This work enables protocol negotiation between HTTP/1.1 and HTTP/2 in its most generic form.
Modifications:
Enable protocol negotiation between HTTP/1.1 and HTTP/2 using typed
negotiation results (`NIOProtocolNegotiationResult`) from the
`NIOTypedApplicationProtocolNegotiationHandler`.
In the HTTP/2 case the negotiation result will return the HTTP/2 connection
channel and the `NIOHTTP2Handler.AsyncStreamMultiplexer` which exposes
inbound streams as an iterable async stream.
Result:
Users will be able to set up negotiated HTTP/1.1 / HTTP/2 connections and
iterate over inbound streams.
Motivation:
Tweaking the formatting of the DocC comments enables syntax highlighting
for parameter names in Xcode
Modifications:
Whitespace changes, capitalisation changes and added a parameter
description for `indexing` in HOACKHeaders `replaceOrAdd`, `add`.
Result:
More readable DocC comments
* Add additional NIOAsyncChannel config
Motivation:
Recent additions to pipeline configuration did not expose some of the
`NIOAsyncChannel` configuration.
Modifications:
Expose `backpressureStrategy`, `isOutboundHalfClosureEnabled`.
I think specific naming and object encapsulation for these parameters should be discussed
later before SPI is removed and we review the API as a whole.
Result:
Pipelie helpers for `NIOAsyncChannel` expose `backpressureStrategy`, `isOutboundHalfClosureEnabled`.
* review comments, re-order parameters
* review comments
* param reordering, missing docs comments
Motivation:
Marking `NIOHTTP2InboundStreamChannels.AsyncIterator` as non-sendable
fails to compile on 5.6 however implicitly non-sendable will do, this is
a nice-to-have.
Modifications:
Move the non-sendable annotation to only apply >= 5.7
Result:
`NIOHTTP2InboundStreamChannels.AsyncIterator` is implicitly non-sendable
on 5.6
* HTTP/2 pipeline NIOAsyncChannel pipeline config
Motivation:
This continues the work to expose functionality which allows users to interact
with HTTP/2 connections via async abstractions and using structured
concurrency.
We build atop of previous work to configure pipelines to deal with
HTTP/2 (with no protocol negotiation) and to wrap connection/stream
channels with `NIOAsyncChannel`s. This will allow users to iterate over
streams and HTTP2Frames.
Modifications:
Provide functions which configure channels and pipelines with the HTTP2
handler, expose a multiplexer for dealing with streams and wrap
connection and stream channels with `NIOAsyncChannel`s.
Result:
Users will be able to create and interact with HTTP/2 connections via
`NIOAsyncChannel`s. Because HTTP/2 is a negotiated protocol and we do
not yet handle it, this is of limited utility.
* review comments
* Update Sources/NIOHTTP2/HTTP2ChannelHandler+InlineStreamMultiplexer.swift
Co-authored-by: George Barnett <gbarnett@apple.com>
---------
Co-authored-by: George Barnett <gbarnett@apple.com>
There are a few places where bugs / poorly structured code crept in during the inline multiplexer work. This attempts to address some of them:
- overly long lines
- mis-named variables
- unnecessary use of generics in one case
* Store HTTP/2 inbound streams as async sequence
Motivation:
In preparation for exposing APIs which surface HTTP/2 connections and
streams using structured concurrency this PR introduces a store for
inbound HTTP/2 streams.
Modifications:
Define types and methods for storing generic types which wrap `Channels`
corresponding to inbound HTTP/2 streams in an async sequence.
Result:
The new types are not yet exposed, this work introduces part of the
framework for future functionality.
* Expose (as spi) helpers for H2 async pipelines
Motivation:
This PR is the first step in exposing APIs which surface HTTP/2 connections and
streams using structured concurrency. This PR exposes the most abstract
spelling of this concept, assuming no particular types/forms for the
types involved in the stream channel types.
Modifications:
* Store a generic `streamInitializer` on the common inbound initializer
which is used to initialize inbound streams before yielding them to
the continuation of streams.
* Expose pipeline configuration functions which assume HTTP/2 but
nothing else about sream channel types.
* Provide internal functions for creating streams without configuring
them. Configuring leads to activation so it can be helpful to allow
that step to be performed manually once any provided initialization
closures have beenn executed.
Result:
Adopters of the new SPI should be able to create outbound and deal with
inbound HTTP/2 stream channels using async streams.
Outside of SPI there should be no changes.
* use synchronous H2 multiplexer accessor
Motivation:
The `ChannelPipeline.SynchronousOperations.configureHTTP2Pipeline(...)`
method added to support synchronously setting up a pipeline to handle HTTP2 with the `StreamMultiplexer` embedded within the `NIOHTTP2Handler` erroneously retrieved the multiplexer via a `.wait()`. This is not permitted and will cause any code which executes it to deadlock.
Modifications:
The synchrounous operation now obtains the multiplexer via
`handler.syncMultiplexer()`
Result:
The code should not deadlock.
* update allocation counts
Motivation:
The `HTTP2StreamChannel` keeps track of how many bytes have been written
and how many are buffered for use in evaluating the 'writability' of the
stream channel. Bytes are considered 'written' or at least no longer
buffered when the write is completed (successfully or errored). In order to make the
determination of when writes are complete across channel handlers we attach a promise to all
writes and deduct adjust the byte counts on completion. Creating and
attaching these promises requires costly allocations.
Modifications:
We can remove the need to create these promises for the new inline
stream multiplexer because the multiplexer and man HTTP2 channel
operations are now all within the `HTTP2ChannelHandler`. This change
calls the `writabilityManager` directly when writes are completed.
Result:
* Fewer allocations are required for HTTP2 writes.
* Writes are considered 'complete' when they leave the `HTTP2ChannelHandler`
Motivation:
HTTP2 flow control only cares about DATA frame sizes so we can be more
accurate and drop the complexity of `flowControlledSize`
Modifications:
`flowControlledSize only returns non-zero sizes for `DATA` frames
Result:
`flowControlledSize only returns non-zero sizes for `DATA` frames
Motivation:
`estimatedFrameSize` aims to estimate the number of bytes a frame will
use on the wire. It includes the 9-octed frame header and is currently
used for flow control estimates but according to spec it shouldn't
include those 9 bytes https://www.rfc-editor.org/rfc/rfc9113.html#section-6.9.1
Modifications:
Replace `estimatedFrameSize` with `flowControlledSize` which ignores the
9-octed frame header and update tests.
Result:
Flow control calculations should be more accurate
Motivation:
CiruclarBuffer always allocates on init as it never has a zero capacity.
It is implemented in such a way that changing this is not trivial. The
compound outbound buffer creates a marked circular buffer
unconditionally on each call but only uses it if there are streams to
drop.
Modifications:
Add a static empty marked circular buffer to the compound outbound
buffer and rely on CoW semantics to avoid the allocation for each call
in cases where there are no frames to drop.
Result:
Fewer allocations.
Motivation:
Remove `NIOHTTP2StreamDelegate` `Sendable` conformance requirement.
This wasn't needed in the first place because `NIOHTTP2Handler`
is not `Sendable`, therefore it never leaves the thread on which it is
created.
The delegate may still be `Sendable` depending on the implementation
but it is not a strict requirement.
Modifications:
Remove NIOHTTP2StreamDelegate Sendable requirement
Result:
Sendable is no longer required for NIOHTTP2StreamDelegate conformance
Motivation:
Allow handlers in the pipeline to be notified when an HTTP2 stream is created or
closed.
Modifications:
Store an instance of a `NIOHTTP2StreamDelegate` on the `NIOHTTP2Handler`
and `InlineStreamMultiplexer` so that it may be called when streams are
created or closed.
Added tests.
Result:
`NIOHTTP2Handler`s init'd with a `streamDelegate` will now call into
that delegate's `streamCreated` and `streamClosed` functions.
* ChannelPipeline H2 inline multiplexer conf funcs
Motivation:
To have parity with the legacy separate `HTTP2ChannelHandler`-`StreamMultiplexer` HTTP2 stream multiplexing model we provide channel pipelineconfiguration functions using the new inline multiplexer.
Modifications:
* New versions of `configureHTTP2Pipeline` and
`configureCommonHTTPServerPipeline` which set up the pipeline using
inline stream multiplexers
* Tests targeting the new functions ported from
`ConfiguringPipelineWithFramePayloadStreamsTests.swift`
Result:
New pipeline configuration conveniences for inline HTTP2 multiplexing
are available.
Motivation:
Less expensive stream multiplexing. To implement direct stream multiplexing (with an incomplete public API) to break up delivery and allow testing.
Modifications:
* Factor out common inbound stream multiplexer functionality from `HTTP2StreamMultiplexer` into `CommonInboundStreamMultiplexer` (first commit).
* Direct stream multiplexing is implemented as `InlineStreamMultiplexer`. It implements both the `HTTP2InboundStreamMultiplexer` and `HTTP2OutboundStreamMultiplexer` protocols.
* We expose `NIOHTTP2Hander.StreamMultiplexer` as a `public` view over the new multiplexer to allow stream creation.
* Adds various `propagate...` functions to relay signals such as read complete to the child channels held by the inline stream multiplexer.
* Adds a stub for `HTTP2StreamDelegate` which will be completed in an upcoming PR. It will be responsible for surfacing stream open/close information.
* Adds conveniences to `NIOHTTP2Handler` for setting up a handler using the inline multiplexer
* Duplicate existing tests and modify to use the inline stream multiplexer where appropriate. `SimpleClientServerFramePayloadStreamTests.swift` and `HTTP2FramePayloadStreamMultiplexerTests.swift` were copied and modified
Result:
Default behavior should be unchanged at this time.
Motivation:
This change prepares for future work to embed the connection multiplexer within the `HTTP2ChannelHandler` which will improve performance by removing the need for passing expensive `InboundUserEvent`s.
Modifications:
This step defines a new protocol (`HTTP2StreamChannelMultiplexer`; named such to avoid confusion with the legacy handler, `HTTP2StreamMultiplexer`) which will later be used to abstract over the inline and legacy multiplexer code but at the moment should not change the logic.
Result:
Behaviour should be unchanged.