Motivation:
Currently swift-nio-http2 is extremely naive with its use of
channelReadComplete calls in HTTP2StreamChannel, firing one
channelReadComplete call per frame read. In high frame load cases this
leads to a lot of excessive channelReadComplete traffic, which can cause
unnecessary time spent in flush calls.
We should try to minimise the amount of time we spend on this
bookkeeping and save the CPU cost.
Modifications:
- Store a linked-list of HTTP2StreamChannels that need to have
channelReadComplete fired on them.
- Fire channelReadComplete based on this linked list.
Result:
Moderate improvement in performance in high-throughput workloads.
Motivation:
While having outbound buffers is necessary, it's pretty important to
clear then when the connection is closed, or the promise will get
leaked. In this case, leaking the promise is usually pretty dang bad,
and tends to cause awkward things like crashes.
Modifications:
- Added hooks to invalidate the CompoundOutboundBuffer.
- Called those hooks in handlerRemoved, where there is no reentrancy
risk.
Result:
Less risk of runtime crash.
Motivation:
While working on other tests I realised that HTTP2StreamID is a type
that can meaningfully be strided, but it does not conform to Strideable.
We may as well add that conformance.
Modifications:
- Added Strideable conformance to HTTP2StreamID.
Result:
Users can stride over HTTP2StreamIDs.
Motivation:
The HTTP2StreamMultiplexer currently passes frames from child streams
through to the rest of the pipeline, and does the same with flushes.
Because HTTP2 is multiplexed, it is highly likely that in any
channelRead cycle multiple child channels will make sufficient progress
to want to flush their results. This means we can end up with multiple,
redundant, flush calls.
It would be better in general to try to reduce the amount of flushing
necessary to no more than once per channelRead cycle.
Modifications:
- Keep track of the channelRead cycle and where we are in it.
- Avoid flushing when we can expect a channelReadComplete.
- Flush on channelReadComplete if necessary.
Result:
Fewer flushes, better performance under high read load.
Motivation:
Stream channels don't get closed when the parent channel closes. This
can lead to some unexpected behaviour for users.
Modifications:
Call receiveStreamClosed on stream channels in the multiplexer when
reciving channelInactive. Added a test to verify the stream is closed.
Result:
Stream channels will be closed when the parent channel is closed.
Motivation:
Previously the HTTP2StreamChannel forwarded all frames to the parent
Channel by way of the abstract Channel existential API. While this was
straightforward, it added unnecessary overhead due to the extra pipeline
steps and the extra indirection of the types providing an inlining
barrier.
Given that in #116 we gave the HTTP2StreamChannel a reference to its
parent multiplexer, we may as well take advantage of this and allow
direct calls from the stream channel into the multiplexer.
Modifications:
Avoided calls to parent.write and parent.flush.
Replaced them with a new interface.
Added new allocation test for this path.
Result:
Slightly better performance.
Motivation:
We recently spotted that in an edge case it was possible for the
outbound frame buffer to incorrectly believe that a flushed frame was in
fact not flushed, and to refuse to give it up until it had encountered a
flush point. This could happen if the frame was flushed but buffered in
the concurrent streams buffer, and was then moved to the flow control
buffer but could not be emitted.
Modifications:
Correctly marked such frames as flushed.
Result:
We won't wedge frames in the buffer.
Motivation:
Our existing model for working out whether a stream channel is active is
a bit too ad-hoc. We "activate" a stream channel once the initializer
has completed so long as the parent channel is active. This approach
is basically reasonable, but it makes it a bit hard to handle stream
closure.
Specifically, in the client case a stream channel may be "active" but
have never sent a frame. In this case we can (and must) close the stream
without sending a frame if the user requests closure. This means we
need to know whether or not the stream is actually open from the
perspective of the parent channel.
Modifications:
- Added new notifications about whether the stream is active on the
network
- Enhanced the stream channel to be more clear about its state.
- Wrote some new tests.
- Fixed old tests that needed updating.
Result:
HTTP2StreamChannel will be more resilient to weird network behaviour.
Motivation:
If the remote peer changes SETTINGS_MAX_CONCURRENT_STREAMS we should ensure that we don't
subsequently violate those bounds.
Modifications:
- Plumb in the SETTINGS_MAX_CONCURRENT_STREAMS change.
Result:
SETTINGS_MAX_CONCURRENT_STREAMS works better
* Allow closing idle StreamChannels.
Motivation:
Users who create stream channels may end up deciding not to use them
and throw them away. We should tolerate this, instead of hanging.
Modifications:
- Rewrote the state management to properly isolate states.
- Allow instant-close when the network hasn't seen the stream.
Result:
Close is faster and works better.
Motivation:
Sometimes when you have a hammer everything looks like a nail.
In this case, my hammer was Futures. But we don't need to use a
Future here: these two classes are tightly coupled, and so we can
safely just call from one to the other.
A side note: while this appears to create a reference cycle, the
act of calling the function in question will actually break that
cycle. So it's all good!
Modifications:
- Remove a future callback.
- Have the stream channel hold a reference to the multiplexer.
Result:
Fewer heap allocations.
Motivation:
When users create a child channel and want to get hold of it,
they will pass a promise to createStreamChannel. This promise
will force a call to map{} and a call to cascade(), both of
which heap allocate. We don't need to have these heap allocations,
and they're easily removed, so we should.
Modifications:
Manually cascade the result.
Result:
Slightly fewer heap allocations in some workloads.
Motivation:
When synthesising data frames we try to emit the flow controlled length of the entire real
data frame on the first synthetic frame. This allows us to correctly police the window management
of that frame, while still synthesising frames.
However, @glbrntt spotted that we were incorrectly repeatedly counting the flow controlled length
of a partial frame. A patch that had been previously added to ensure we only counted it once was
not working correctly.
Modifications:
- Adjusted the location of the call to flowControlledLength.
Result:
Correct accounting of flow controlled length
Motivation:
We were copying HTTP headers around quite a lot when transforming from HTTP/1 to HTTP/2 and
back. Due to the different underlying representations we cannot get away from needing to do
one copy, as the backing array storage is of a different type, but we were frequently incurring
CoWs as well that were just totally unnecessary.
Modifications:
- Refactored the header code to work more confidently on HPACKHeaders.
- Removed some mutating functions that triggered unnecessary CoWs.
- Improved HPACKHeaders(httpHeaders:) initializer to avoid unnecessary intermediate array
- Improved HTTPHeaders(requestHead:protocolString:) to avoid CoWs and reallocations
- Improved HTTPHeaders(responseHead:) to avoid CoWs and reallocations
Result:
Fewer heap allocations
Motivation:
This is basically a similar issue to #104: we have a CoW data structure (ByteBuffer) in some of
these states, and when calling append on them they force an unnecessary CoW. We can reproduce the
fix from that patch, which is to define an empty state and swap into it before we run the append.
We also define a helper that ensures that we don't screw this up.
Modifications:
- Added new appending state to HTTP2FrameDecoder
- Added helpers for avoiding a CoW
- Avoided CoW in HTTP2FrameDecoder.
Result:
Fewer unnecessary copies
Motivation:
Anything that passes through a NIO pipeline in high volume that is not special-cased by NIOAny
needs to have careful attention paid to its size. This is because if it's more than 3 64-bit words
wide (24 bytes), it will need to be heap-allocated to be stuffed into the Any case of the NIOAny.
Sadly, HTTP2Frame was 44 bytes wide: altogether too wide for the pipeline. This was forcing heap
allocations each time a frame was sent or received in the pipeline, which is not so good.
To avoid this problem we normally turn our data structures into a CoW box. We want to do that
here as well, but we need to be a bit careful. Many parts of the code access the `streamID` field
frequently, and placing the stream ID into the CoW box will slow those accesses down by requiring a
memory load from a non-stack location. Additionally, code frequently checks the payload discriminator
byte, which we would like out of the box as well if at all possible.
It turns out that we have a neat tool at our disposal to achieve this: `indirect case`. This allows
us to ask the Swift compiler to box a structure *when stored in an enum case*. The effect is to shrink
the size of the enumeration when passed around as an enum, but nonetheless allow the contained objects
to be identical in form and API to when they were unboxed. It's very helpful here.
This shrinks the size of the HTTP2Frame data structure from 44 bytes to 18 bytes, dropping the size of
the payload enumeration to 10 bytes and leading to a 10% perf gain in some microbenchmarks.
Modifications:
- Placed large HTTP2Frame.FramePayload cases into a box.
Result:
Performance improvements!
Motivation:
RFC 7540 Section 6.9: "WINDOW_UPDATE can be sent by a peer that has sent
a frame bearing the END_STREAM flag. This means that a receiver could
receive a WINDOW_UPDATE frame on a "half-closed (remote)" or "closed"
stream. A receiver MUST NOT treat this as an error (see Section 5.1)."
Previously WINDOW_UPDATE frames received in this state would be treated
as an error.
Modifications:
- Allow frames to be ignored if they are for a stream which has been
closed.
- Add a test to verify WINDOW_UPDATE on a closed stream.
- Update tests which relied on a stream error in this case.
Result:
More compliant code.
Motivation:
As noted in #105, I spotted that we were heap-allocating an array
when parsing the frame header. That heap allocation isn't necessary, we
can just write directly into an Int, which should save us some heap spray.
Modifications:
- Rewrote code to avoid heap allocating array and instead to use Int.
- Elided some bounds checks by using an unsafe pointer, since I was
already here and it saved about 1% performance in a hot loop.
Result:
Fewer heap allocations on the hot code path.
Motivation:
When benchmarking the HTTP/2 implementation I noticed that we were
performing a large number of CoW operations on the Dictionary that backs
the ConnectionStreamState structure: specifically, once per frame sent or
received.
This is substantial and unnecessary allocation overhead that drags down
the performance of the program, sprays the heap with small allocations, and
generally just leads to nasty performance costs with no gain.
Sadly, this turns out not to be the easiest CoW to get rid of, because
the ConnectionStreamState structure is stored in associated data on the
connection state machine state enumeration. This means that our usual tricks
for avoiding the CoW (such as swap()) no longer work.
The only solution is to add a new state that corresponds to no state at all
so that we can make the connection state go away while we mutate it. This is
all a bit gross, frankly. Unfortunately, the act of making this simple change
leads to a huge diff as we have to tweak basically every state machine
function in order to ensure that it does the right thing.
Modifications:
- Added a function to control CoWing the state machine.
- Used that function basically everywhere.
- Made sure that function had assertions.
- Annoyingly had to increase the visibility of a bunch of structs.
Result:
Fewer CoWs, better performance, sadder code reviewers.
Motivation:
We would previously error if clients emitted a GOAWAY frame that had
a last stream ID set to the max value. This is a bit unnecessary, not
least given that we emitted those frames ourselves! In fact, this error
would mask real server protocol errors if we hit them.
Modifications:
- Allowed max stream ID as the last stream ID.
- Wrote a test to verify this.
Result:
Fewer unnecessary protocol errors.
Motivation:
RFC 7540 requires that compliant specifications emit errors if content-length has been incorrectly
set. We should have this behaviour by default, though we should allow it to be disabled if necessary.
Modifications:
- Added content-length checking.
- Added flag to disable content-length checking.
Result:
Better RFC 7540 compliance.
Motivation:
When we're validating that settings are in their bounds, we should probably endeavour to
express those bounds correctly.
Modifications:
- Fixed the bounds checks on SETTINGS_INITIAL_WINDOW_SIZE and SETTINGS_MAX_FRAME_SIZE.
- Added regression tests.
Result:
Better correctness.
Motivation:
RFC 7540 forbids the use of connection-specific header fields, except for TE sent
with the value "trailers". We should police that.
Modifications:
- Added extra policing around regular header fields.
Result:
Better validation
Motivation:
RFC 7540 does not allow empty :path pseudo-headers. We should police this.
Modifications:
- Added a check that :path isn't empty.
Result:
Better RFC 7540 validation.
Motivation:
HTTP/2 header blocks have a certain set of pseudo-headers that are mandatory
and allowed on them. We currently don't enforce that, which makes it possible to send
malformed requests or responses, as well as to have to handle them. That's not great.
Modifications:
- Added enforcement of the allowed pseudo-header fields.
Result:
Better pseudo-header field enforcement.
Motivation:
RFC 7540 requires that HTTP/2 pseudo-headers must be first in a HTTP/2
header block, and must occur before any regular headers. We should enforce
that requirement.
Modifications:
- Added checking that pseudo-headers are first in a header block.
Result:
Better RFC 7540 validation.
Motivation:
Zero length SETTINGS frames are permitted by RFC 7540 but the frame
parser currently throws a FRAME_SIZE_ERROR.
Modifications:
- Allow zero length SETTINGS frames to be parsed
- Added a test
Result:
Parsing zero length SETTINGS frames don't throw an error.
Motivation:
RFC 7540 forbids uppercase characters in header field names, but we
currently allow them. We shouldn't.
This is the first in a series of patches that will validate header blocks
when reasonable. As a result, it seems larger than necessary, as it adds
a bunch of scaffolding for extending with further validation code.
Modifications:
- Added header field validation scaffolding.
- Validates that header field names do not contain uppercase chars.
- Allows sending RST_STREAM frame before stream setup.
Result:
Better header field validation.
Motivation:
RFC 7540 requires that the END_STREAM bit be set on a HEADERS frame that
sends trailers. We should enforce that.
Modifications:
- Require that the END_STREAM bit is set on trailers.
Result:
We reject more incorrect flows.
Motivation:
The stream multiplexer was incorrectly eating channelActive on its own
channel, and failing to pass them on to subsequent channel handlers, if
there were any.
Modifications:
- Passed channelActive on from stream multiplexer.
Result:
Easier to handle things on the parent channel.
Motivation:
In the future we'll want to use PRIORITY frames to provide feedback on
how we emit data. Additionally, RFC 7540 forbids certain kinds of
PRIORITY frame, which right now we tolerate receiving. We can design a
minor PRIORITY shim to ensure that we have a code path for PRIORITY data
to be passed around, and then use this shim to enforce RFC 7540's
requirements.
Modifications:
- Added support for PRIORITY frame data inbound.
- Enforce that frames may not establish self-dependency.
Result:
Better policing of RFC 7540 constraints.
Motivation:
SETTINGS_MAX_FRAME_SIZE is changeable: we should allow that change to
occur.
Modifications:
- Added fields for communicating MAX_FRAME_SIZE changes.
- Update the encoders/decoders as those settings change.
- Throw errors from the encoders/decoders if violated.
Result:
Users and remote peers can change MAX_FRAMES_SIZE.
Motivation:
The StreamMultiplexer and StreamChannels are responsible for sending
WINDOW_UPDATE frames, but they were never told if the user changed the
value of SETTINGS_INITIAL_WINDOW_SIZE. They should be.
Modifications:
- Send user events when SETTINGS_INITIAL_WINDOW_SIZE changes.
- Use those window events to change the target window size in
HTTP2StreamChannel.
- Keep track of the last stream window size we knew.
Result:
Less chance of flow control mess.
Motivation:
We mustn't allow CONTINUATION frames to be sent on invalid stream IDs.
Modifications:
- Police that the CONTINUATION frame raw stream ID matches the previous
frame's raw stream ID.
Result:
Better conformance to the RFC
Motivation:
Receiving a CONTINUATION frame at the wrong stage of a connection is
a PROTOCOL_ERROR, but out of an abundance of caution we were categorising
it as an INTERNAL_ERROR. We should be more confident about our error
categories.
Modifications:
- Changed INTERNAL_ERROR to PROTOCOL_ERROR.
- Added a test for this error case.
Result:
More confidence, more style, more pizazz.
Motivation:
When the remote peer changes SETTINGS_INITIAL_WINDOW_SIZE, this change
affects the flow control window sizes of all existing streams (as though
they were created with this new initial window size). We should respect
those flow control changes.
Modifications:
- Propagated changes in SETTINGS_INITIAL_WINDOW_SIZE.
- Made NIOHTTP2ConnectionStateChange internal.
- Added support for changing initial window size.
Result:
SETTINGS frames that change initial window size now work properly.
Motivation:
In certain cases it was possible for preamble to be sent once; this
would lead to frames getting sent more than once which in turn would
break state machines.
Modifications:
- Check the state of the connection before sending preamble.
- Include a test to check.
Result:
More correct implementation
Motivation:
DATA frames with zero-length application data would cause the state
machine to wait for more bytes to continue. This could cause consuming
code to deadlock.
Modifications:
Updated the frame parser to only require more data when there are
remaining bytes in the payload and there are zero readable bytes.
Result:
DATA frames with zero-length application data can be parsed.
Motivation:
When setting the stream window size for a stream which had data but
couldn't write it (because of a zero window size) the stream would be
marked as flushable. Setting the window size to zero again would not
mark it as unflushable. On the following window (non-zero) resize it
would be marked as flushable again. However, since this is preceeded by
an assertion that it wasn't already marked as flushable it would cause a
crash.
Modifications:
- Mark the stream as unflushable if it previously had data which it
couldn't write.
Result:
Fewer crashes
Motivation:
PRIORITY frames aren't really sent on a single stream, so we shouldn't
attempt to deliver them to the child channels. Instead, we deliver them on
the parent channel.
Modifications:
Moved PRIORITY frames to the parent channel.
Result:
Less confusion about where PRIORTY frames go
Motivation:
When we spiked out these codecs we were missing a number of error handling
paths, which meant that erroneous input would lead to crashes. While we
don't expect these handlers to have to face that kind of input, we should
still aim to tolerate it where doing so is reasonable.
Modifications:
- Replaced all force unwraps and preconditions with throwing.
Result:
Fewer crashes on bad input.
Motivation:
We attempted to use the NIO channel pipeline to spread out the HTTP/2
implementation across a number of channel handlers. Unfortunately, due
to the concerns of reentrancy it's not really safely possible to do this:
it's too easy for the pipeline ordering to become so confused that the
implementation ends up incorrect.
For this reason, we are going to squash together the three handlers that
provide a complete HTTP/2 protocol implementation into just one.
Modifications:
- Move the ConcurrentStreamsHandler and FlowControlHandler into the
HTTP2Handler.
- Update setup and test code accordingly.
Result:
More correct implementation
Motivation:
Code should be able to compile.
Modifications:
- Add necessary force-unwraps to ByteBufferViews.
- Remove use of now-dead HTTPHeaders storage and indices API.
Result:
No compile errors.
Motivation:
As discussed in our HTTP/2 types manifesto, it is helpful to run more
metadata through the HTTP/2 pipeline. This makes it easier to write
ChannelHandlers that fully participate in the HTTP/2 state machine
while avoiding needing to too tightly couple the handlers.
Modifications:
- Added new HTTP/2 pipeline data types.
- Removed HTTP2Frame.FrameFlags, moved flags into relevant payloads.
Result:
Right now, not much. All tests pass with new payload types. The full
data path rewrite will follow in a separate patch, as this one is large
enough.
Motivation:
Rather than rely on users to get a bunch of stuff right when configuring
their HTTP/2 pipelines, it's helpful to insert the handlers in the right
order in a helper function.
Modifications:
Provide a helper configurator that inserts handlers correctly.
Result:
Easier to configure HTTP/2 pipelines.
* Updated to use SwiftNIO 1.10+ to gain access to HTTPHeaders internals.
* Add pure-Swift HTTP/2 protocol implementation.
Motivation:
Currently we use nghttp2 for our basic protocol implementation. This is
plenty workable, but provides us a number of limitations. It adds
complexity to our build system, provides us with external dependencies we
have little control over, limits our users' ability to express low-level
protocol semantics if they so wish, causes us to heap-allocate like crazy over
the lifetime of a connection, and brings a world of pain around reentrancy.
This set of limitations has motivated a desire to move away from using
nghttp2. This is a part of that dream.
Modifications:
- Add pure Swift protocol implementations.
- Test them.
Results:
Another step towards protocol independence.
* Initial basic parser code.
* Adding unit tests.
* Add NIOHTTP2FlowControlHandler
Motivation:
One of the things that nghttp2 used to do for us was to handle buffering
DATA frames until flow control allowed them to go out. For users that
want that behaviour, we need to replace the nghttp2 code with a new
ChannelHandler that can do this work.
Modifications:
- Added NIOHTTP2FlowControlHandler.
Result:
Users will have the same feature set as they did with nghttp2.
* Generate Linux test information.
* Documentation comment.
* Updated new tests from master to use new payload types.
* Updated following review.
Notable changes:
- Implemented unit tests for the ALTSVC (0xa) and ORIGIN (0xc) frame types.
- Additional DATA frames are synthesized to wrap individual payload chunks as they arrive. If the payload of a DATA frame with 4MB data arrives in 4 separate 1MB chunks, the decoder will emit 4 DATA frames, with only the last containing the END_STREAM flag (if that was set on the incoming frame).
- HEADERS / PUSH_PROMISE frames and any following CONTINUATION frames are now handled properly: header fragments from all frames are gathered up into a single buffer. Once a frame with END_HEADERS is encountered, the resultant accumulated buffer is sent for decoding along with the flags and stream ID of the original HEADERS / PUSH_PROMISE frame.
- HPACK encoders/decoders now live in the frame encoder/decoder types, rather than being attached to a stream.
* Updated Linux tests.
* Headers placed in relevant files.
* Add pure-Swift HTTP/2 protocol implementation.
Motivation:
Currently we use nghttp2 for our basic protocol implementation. This is
plenty workable, but provides us a number of limitations. It adds
complexity to our build system, provides us with external dependencies we
have little control over, limits our users' ability to express low-level
protocol semantics if they so wish, causes us to heap-allocate like crazy over
the lifetime of a connection, and brings a world of pain around reentrancy.
This set of limitations has motivated a desire to move away from using
nghttp2. This is a part of that dream.
Modifications:
- Add pure Swift protocol implementations.
- Test them.
Results:
Another step towards protocol independence.
* Revamped frame decoder state machine and API. Now uses separate input and output methods to manage multiple frames in a single buffer.
* Updated Linux tests.
* Bumped swift-nio version to 1.12.0 and updated `HTTPHeaders` -> `HPACKHeaders` conversion initializer to directly copy the buffer and map the header name/value indices.
* Set up HTTP2Parser in handlerAdded if the channel had been previously activated. (#36)
By setting up the handler in the handlerAdded hook, HTTP2Parser supports
being added dynamically in a channelRead event, after the channel has sent
the channelActive event.
(cherry picked from commit 88bd6d369a)
* Minor tweaks to get the tests passing
* Initial integration here
* Minor clearing up of the handler
* Get the tests compiling
* Fix header issues.
We now pass the frame parser to the various setting operations to let it
update the state. We also fixed some issues with specific settings.
* Remove ngthttp2-based impl, clean up stream ID
* Tests with new HTTP2StreamID
* Simple test cleanup
* Get remaining non-core tests passing
* Allow GOAWAY even when fully quiesced
* We don't buffer outbound frames any more
* Emit StreamClosed events on GoAway frame
* Notify stream creation and closure
* This test started failing
* Goodbye, C code! 🎉
* Send PING ACK automatically
* Updated based on PR feedback.
* Correctly handle 1XX responses
* Add SETTINGS_MAX_FRAME_SIZE support to flow controller
* Correctly account for flow control
* Define ConcurrentStreamsHandler
* Prepare for signalling connection state changes
* Better state change message propagation
* Refactor to use result with effect everywhere
* Don't lose flow control info on stream error
* Add basic flow control management to stream multiplexer
* Better pipeline in sample server
* Clean up some reentrancy concerns
* Move to Swift 5 and NIO 2
* Move to new Swift 5 for CI
* Allow wider range of choices of years
* Catch up to NIO 2 again