Motivation:
When remote peers set the value of HEADER_TABLE_SIZE to any non-default
value, or when we update it, we should respect that value when we're
emitting headers.
Unfortunately, right now we don't. In particular, we manage to update
the wrong setting: when the peer sets HEADER_TABLE_SIZE we bound the
maximum size of the dynamic table _they_ can use, not the maximum size
_we_ can use. That's incorrect by the spec, which says:
> This setting allows the sender to inform the remote endpoint of the
> maximum size of the compression table used to decode field blocks,
> in units of octets. The encoder can select any size equal to or less
> than this value by using signaling specific to the compression
> format inside a field block (see [COMPRESSION]).
If a peer sent us SETTINGS_HEADER_TABLE_SIZE with a value of 0, we'd
restrict _them_ to only using a maximum table size of 0, instead of us.
This is wrong.
Additionally, when we updated the encoder we used the wrong method, so
the encoder would never send dynamic table size changes. This was also
incorrect!
In general this managed to get missed because, as RFC 9113 notes:
> Implementers are advised that reducing the value of
> SETTINGS_HEADER_TABLE_SIZE is not widely interoperable. Use of the
> connection preface to reduce the value below the initial value of
> 4,096 is somewhat better supported, but this might fail with some
> implementations.
It turns out one of those implementations this might fail with is us!
The result, however, is that very few implementations actually try to
reduce the value of the header table size, so we rarely ran into this
issue. nginx does actually try this in some cases, however, which is how
we found this problem.
Modifications:
- Correctly invert the application of the value of
SETTINGS_HEADER_TABLE_SIZE
- Correctly use `setDynamicTableSize` on HPACKEncoder instead of just
setting the field manually.
- Deprecate the invalid method of setting the field on HPACKEncoder.
- Add some HTTP/2-level tests that ensure we correctly handle these
changes.
Result:
Vastly better handling of peers reducing the value of
SETTINGS_HEADER_TABLE_SIZE.
Motivation:
channelActive must always precede channelInactive. Unfortunately, this
isn't guaranteed right now: if we happen to get channelInactive as a
result of our writing the preamble we'll fire them in the wrong order.
Many systems can tolerate this, but we should avoid doing this anyway.
Modifications:
- Added a state enum to keep track of the state we're in
- Use that state enum to ensure we deliver active/inactive in the right
order
- Additionally police other unexpected active/inactive behaviours
Result:
We'll appropriately police the state.
Motivation:
The stream channel updates its writability manager when issuing a write
to the parent channel and when the write promise has been succeeded.
If the write promise has already been succeeded then the writability
manager can be updated in the wrong order which can lead to underflow.
Modifications:
- Use signed arithmetic in the writability manager and allow pending
bytes to become (briefly) negative.
Result:
The writability manager's pending bytes shouldn't underflow.
Motivation:
When we added new content length verification and new errors, we didn't
update the places that were handling the old error. This code updates
that logic to ensure that we don't crash.
Modifications:
Add new internal protocol to which the content length validation errors
conform.
Catch that protocol instead.
Result:
No crashes on invalid content-length
Motivation:
Currently http2 ignores content length when handling a response to a HEAD request and handling a 304 response.
Modifications:
Changing ContentLengthVerifier and any functions called
---------
Co-authored-by: George Barnett <gbarnett@apple.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
Using indirect cases makes unwrapping and rewrapping HTTP/2 frames more
expensive than it needs to be. As FramePayload.Data is essentially
always stuffed into a FramePayload enum, we may as well just class-back
it and avoid the extra allocs.
Modifications:
Make FramePayload.Data class-backed
Result:
Fewer allocations in many use-cases
Motivation:
We don't always require an array of header values to be extracted.
Sometimes we just need to be able to iterate through them. For 'regular'
header values we incur an allocation for the array, for values in their
canonical form we incure at least two allocations. We can do better than
this by providing a header value sequence.
Modifications:
- Add new API to `HPACKHeaders` for getting a sequence of header values
which can optionally be in their canonical form.
- Update the API of the two existing subscripts to use this new API. For
`subscript(canonicalForm:)` we save an allocation by not going via
`subscript(name:)`.
Result:
- Fewer allocations in `subscript(canonicalForm:)`
- Header values can be iterated without allocating
Motivation:
We discovered that this code path can result in an arithmetic overflow
in the case where the content-length header has INT_MIN value. Since
negative content-lengths don't have any meaning anyway we may as well
throw if we encounter one so the decoding can be aborted.
Modifications:
* ContentLengthVerifier init throws a `ContentLengthHeaderNegative` error
when the decoded value is < 0.
* ContentLengthVerifier init throws a `ContentLengthHeaderMalformedValue` error
when the value cannot be decoded, e.g. it is out of bounds for Int or is
an invalid string.
Result:
We will no longer panic for INT_MIN content-lengths and will fail
decoding if one of various invalid values is encountered.
Motivation:
#fileID introduced in Swift 5.3, so no longer need to use #file anywhere
Modifications:
Changed #file to #filePath or #fileID depending on situation
Motivation:
NIOSendable was deprecated in https://github.com/apple/swift-nio/pull/2291
as the earliest supported Swift version in NIO land is now 5.5.
Modifications:
- s/NIOSendable/Sendable
Result:
Avoids deprecation warnings when the above patch is released.
Motivation
Documentation is nice, and we can help support users by providing useful
clear docs.
Modifications
Add Docc to 5.6 and later builds
Make sure symbol references work
Add overview docs
Result
Nice rendering docs
Motivation:
Nowhere in the PUSH_PROMISE code do we explicitly check whether or not
we're a client or a server, and we don't provide special handling for
SETTINGS_ENABLE_PUSH contingent on that fact. As a result, we do
technically allow clients to push. This eventually gets caught, but not
until we've created an idle stream, which we shouldn't do.
Modifications:
- Forbid clients from pushing.
Result:
Clients won't be allowed to push.
Co-authored-by: George Barnett <gbarnett@apple.com>
* Lower allocation limits
Our recent fixes reduced our allocation count, which is good.
* fix code soundness check
motivation: code should be sound!
changes:
* update one case of inappropriate langauge
* update header years check regex
(cherry picked from commit a89e8ae4e0)
Co-authored-by: tom doron <tomer@apple.com>
Motivation
The HTTP2FrameDecoder is a complex object that was written early in the
development of swift-nio-http2. Its logical flow is complex, and it
hasn't been meaningfully rewritten in quite some time, so it's difficult
to work with and understand.
Annoyingly, some bugs have crept in over the years. Because of the
structure of the code it can be quite difficult to understand how the
parser actually works, and fixing a given issue can be difficult.
This patch aims to produce a substantial change to the HTTP2FrameDecoder
to make it easier to understand and maintain in the long run.
Modifications
This patch provides a complete rewrite of HTTP2FrameDecoder. It doesn't
do this by having a ground-up rewrite: instead, it's more like a
renovation, with the general scaffolding kept. The rewrite was performed
incrementally, keeping the existing test suite passing and writing new
tests when necessary.
The following major changes were made:
1. New states and edges were added to the state machine to handle
padding.
Prior to this change, padding was handled as part of frame payload
decoding. This is not totally unreasonable, but it dispersed padding
management widely and made it easy to have bugs slip in. This patch
replaces this with a smaller set of locations.
Padding is now handled in two distinct ways. For HEADERS and
PUSH_PROMISE frames, trailing padding is still stripped as part of
frame payload decode, but it's done so generically, and the padding
bytes are never exposed to the individual frame parser. For DATA,
there is a new state to handle trailing padding removal, which
simplifies the highly complex logic around synthesised data frames.
For all frames, the leading padding byte is handled by a new
dedicated state which is used unconditionally, instead of attempting
to opportunistically strip it. This simplifies the code flow.
As a side benefit, this change means we can now accurately report the
padding used on HEADERS and PUSH_PROMISE frames, even when they are
part of a CONTINUATION sequence.
2. The synthesised DATA frame logic has been substantially reworked.
With the removal of the padding logic from the state, we now know
that so long as we have either got a byte of data to emit _or_ the
DATA frame is zero length, we will always emit a frame. This has made
it simpler to understand the control flow when synthesising DATA
frames.
3. The monolithic state switch has been refactored into per-state
methods.
This helps manage the amount of state that each method can see, as
well as to logically split them up. In addition, it allows us to
recast state transformations as (fairly) pure functions.
Additionally, this allowed the larger methods to be refactored with
smaller helpers that are more obviously correct.
4. The frame payload parsers have been rewritten.
The main goal here was to remove preflight length checks and unsafe
code. The preflight length checks cause trouble when they disagree
with the parsing code, so we now rely on the parsing code being
correct with regard to length.
Relatedly, we previously had two separate places where we
communicated length: a frame header length and a ByteBuffer length.
This was unnecessary duplication of information, so we instead use a
ByteBuffer slice to manage the length. This ensures that we cannot
over-parse a message.
Finally, in places that used unsafe code or separate integer reads,
we have refactored to stop using that unsafe code and to use combined
integer reads.
5. Extraneous serialization code has been extracted.
The HTTP2FrameEncoder was unnecessarily in this file, which took a
large file and made it larger. I moved this out.
Result
The resulting parser is clearer and safer. Complex logic has been broken
out into smaller methods with less access to global data. The code
should be generally clearer.
Motivation:
We don't currently support ALTSVC and ORIGIN frames. At the moment when
receiving or attempting to write these frames we trap. Trapping when
receiving an unsupported frame can lead to DoS attacks. Moreover these
frames are non critical so can safely be ignored.
Modifications:
- Forward inbound and outbound ALTSVC and ORIGIN frames to the
connection state machine
- The connection state machine now ignores inbound frames of this type
- The connection state machine traps on outbound frames of this type (as
per the current behaviour)
- Document this behaviour on `HTTP2Frame.FramePayload`
- Tests and fuzz testing failure case
Result:
We don't trap when receiving unsupported frames.
* Validate HEADERS frame length accounts for priority data
Motivation:
When parsing a HEADERS frame payload which includes priority data the
expected length of the frame is not validated to ensure that it is large
enough to account for the stream data. This can lead to the expected
payload length being negative.
Modifications:
- Validate that when stream priority data is present that the frame
length is at least that size
- Add fuzz testing failure case
Result:
The frame decoder will throw a protocol error when parsing a HEADERS
frame if the length of the frame is less than the number of bytes
required for stream priority data and the priority flag is set.
* Add additional tests
* Fix weirdo formatting
Motivation:
The `wroteFrame` flag in `HTTP2ChannelHandler` indicates whether a frame
has been written. This flag is checked before flushing in order to avoid
unnecessary flushes. Unfortunately this is only ever set to `true`.
Modifications:
- Add a `flushIfNecessary` to check and toggle `wroteFrame` and flush if
necessary
- Add a test
Result:
- Few unnecessary flushes
- Resolves https://github.com/apple/swift-nio-http2/issues/245
In rare cases the `HTTP2ChannelHandler`s method `unbufferAndFlushAutomaticFrames` and the `HTTP2StreaMultiplexer`s `newConnectionWindowSize` method were recursively calling themselves. This was causing a stack overflow. To protect our selves from this stack overflow I added a variable to protect ourselves against reentrancy inside the `unbufferAndFlushAutomaticFrames` method
### Motivation
In the AsyncHTTPClient the read event is not always forwarded right away. We have seen instances, in which we see a `HTTPClientError.remoteConnectionClosed` error, on requests that finish normally. https://github.com/swift-server/async-http-client/issues/488
On deeper inspection, I noticed: If there is no unsatisfied read event, when a stream is closed, the pending reads are not forwarded. This can lead to response bytes being ignored on successful requests. NIOHTTP2 should behave as NIO and force forward all pending reads on channelInactive.
### Changes
- Forward all pending reads on channelInactive even if no read event has hit the channel
### Result
All requests will receive the complete request body.
Motivation:
When we hit a stream error on an outbound frame, we don't currently
distinguish between them and channel errors. This makes it impossible
for anyone to tell them apart. It also makes it impossible for the
multiplexer to deliver these errors into the relevant stream channels
that triggered them, making it essentially certain they'll be lost.
Better diagnostics would be good, so we are providing them.
Modifications:
- Add new StreamError type that carries a stream ID and an underlying
error.
- Emit this StreamError type for outbound stream errors.
- Deliver this StreamError type into the relevant child channels when
possible.
Result:
Better diagnostics for stream errors.
Motivation:
With NIO 2.32.0 we broke the core NIO module up into modules that split
apart the POSIX layer and the core abstractions. As a result, this
package no longer needs to express a hard dependency on the POSIX layer.
Modifications:
- Rewrote imports of NIO to NIOCore.
- Added NIOEmbedded imports where necessary in tests.
- Note that the main modules still depend on NIO, which is necessary
for backwards-compatibility reasons. This dependency is unused.
Result:
No need to use NIOPosix.
### Motivation:
`removeHandlers(channel:)` was deprecated in NIO 2.32.0.
### Modifications:
- Raise minimum required `NIO` version to 2.32.0
- Use `removeHandlers(pipeline:)`
### Result:
We don't use deprecated API.
Motivation:
SwiftNIO 2.27.0 added synchronous channel options. We can use these if
available when creating a stream channel to avoid a future allocation.
Modifications:
- 'getAutoReadFromParent' is synchronous when possible and now takes a
closure to handle the result.
- Update allocation counts (and sort them to make updating them easier,
this also includes switching the order we run test_1k_requests
interleaved and noninterleaved)
Result:
Fewer allocations.
Motivation:
SwiftNIO 2.27.0 added support for synchronous channel options allowing
callers to get options synchronously -- saving a future allocation -- if
they know they're on the correct event loop. 'HTTP2StreamChannel' should
support this.
Modifications:
- Add 'HTTP2StreamChannel.SynchronousOptions' with conformance to
'NIOSynchronousChannelOptions'
Result:
Callers can get and set options synchronously on 'HTTP2StreamChannel'
Motivation:
The stream channel configure function uses a chain of futures where the
same can be achieved in fewer futures.
Modifications:
- Merge the future chains where possible in HTTP2StreamChannel.configure
Result:
A 1.3% reduction in instructions in server_only_10k_requests_1_concurrent
Motivation:
To save myself some lines of code I wrote a function that was generic
over a protocol to copy out a pair of fields from a wide range of types.
It turns out this generic was triggering a retain/release on the state
machine states, which triggers 12 ARC operations total (6 retain/release
pairs).
Removing this generic and just, you know, calling a function with some
arguments turns out to save us a bunch of this ARC traffic.
Modifications:
- Remove the generic initializer of StateMachineResultWithEffect.
Result:
Approximately 1% performance improvement in hot benchmarks.
Motivation:
The OutboundFlowControlBuffer is responsible for managing DATA and
HEADERS frames for all streams in order to ensure that we obey HTTP/2
flow control rules, even when users don't. This object is therefore on
the data path for the vast majority of frames, and is extremely
performance sensitive.
Unfortunately, the current algorithm has some nasty performance cliffs.
Right now it has the awkward property of making flushes take an amount
of time linear in the number of streams on the connection, not the
number of streams that had had frames sent on them. The result is that
connections with highly parallel numbers of streams see extremely poor
performance when flushing, a problem that is exacerbated if other parts
of the HTTP/2 stack fail to coalesce those flushes.
We can clean this up in a few ways, but the easiest way is to just keep
track of which streams have done I/O since the last flush. While we're
there, we can make a few other optimisations to ensure we only flush
data on streams we are actually processing, to further reduce the risk
of wasting our time processing unnecessary work.
Modifications:
- Add a Set to keep track of where we've done writes since the last
flush.
- Streams whose flow control window goes to zero stop being writable.
- Cheaper and more accurate calculation of zero-length writes, which
avoids the possibility of awkward stalls with zero-length DATA frames
and END_STREAM.
- Stop doing math about the number of flushed bytes, we don't use that
information any more.
Results:
An approximately 10% performance gain on the 100 concurrent streams
server-only benchmark. The relative performance gain shifts with the
number of active streams, but it should be positive in all cases.
Motivation:
The outbound flow control buffer currently does a linear scan through
the pending data objects to work out how many bytes were buffered. Let's
burn an integer and just calculate these on the way in, making flushes
way cheaper.
Modifications:
- Update the number of bytes when we buffer the write, and make flushes
cheaper.
Result:
Moderate performance improvement in high throughput server benchmarks
(around 4%).
Motivation:
The logic for doing bulk stream teardown in the ConnectionStreamsState
was always a bit janky: we'd grab all the stream IDs out of the map,
filter out anything that was too small, insert them one-by-one into a
circular buffer, and then report back. I basically just translated that
directly into StreamMap, but on StreamMap this potentially performs very
poorly, as attempting to find the pivot point becomes a linear scan
through the stream data even when there are _loads_ of streams.
This patch swaps over to add a specialized function for bulk-removal of
streams. The specialized function passes the slice of data to be removed
to the caller so that they can compute on it. It does this by a closure
to try to avoid a CoW where possible.
While we're here I tried to address the loop over the CircularBuffer of
recently reset streams. This flushed out an awkward bug that has existed
in our recently reset streams logic for a very long time, which is that
while we _tried_ to maintain the size of the circular buffer, in
practice we misunderstood the CircularBuffer invariants and so this
never worked. I've added a bunch of unit tests for that logic and fixed
it up.
These two changes together will improve performance in stream bulk
teardown. This is an uncommon case (it only happens on GOAWAY), but it's
still good to make that faster.
Modifications:
- New operation on StreamMap
- New prependWithoutExpanding(contentsOf:) operation
- Unit tests for the circular buffer and stream map logic.
Result:
Better performance on bulk stream teardown.
Motivation:
It's not possible (at least trivially) from the public API to determine
which peer in a connection initiated a given stream ID. In some cases
it's possible with prior knowledge (i.e. in a given application the
client may always initiate streams), however, such conditions aren't
guaranteed to always hold.
Modifications:
- Add `isClientInitiated` and `isServerInitiated` computed properties to
`HTTP2StreamID`.
- Add a few tests.
Result:
Users can easily get the answer to the question 'did a client/server
create this stream?'
Motivation:
When working with HTTP/2 we frequently have a need to store "per-stream"
state. This is state that is independently reproduced once per stream.
We often need to look up this state by stream ID, and so we are
motivated to store this state as efficiently as possible.
Naively, Dictionary seems like a useful data type for this. However,
Dictionaries are not free. The cost of hashing in order to index into a
Dictionary can be substantial. This is both because the hashing function
itself is branchy and complex, but also because the dictionary access is
very unfriendly to the branch predictor and the memory caching systems.
We can take advantage of the fact that if you split streams into client
and server namespaces, stream IDs are strictly ordered. That is, streams
are created in order of increasing stream ID. While streams are
_retired_ out of order, at no point will a CircularBuffer of stream IDs
ever be unordered.
This unlocks a very powerful data structure for us: the ordered "Array"
(in our case actually CircularBuffer). An ordered Array supports two
powerful lookup tools. Firstly, it supports the mighty binary search.
This means the absolute worst-case searching performance for an ordered
Array is log(n) in the size of the Array. Finding a stream by stream ID
in an Array of one million streams would take around 20 steps: extremely
cheap.
For smaller sizes, however, we unlock the one true searching function:
linear scan. On modern CPUs, performing simple computations (such as
checking if one number equals another) is orders of magnitude faster
than looking data up in memory. More importantly, modern CPUs can often
effectively compute multiple lookups at once thanks to their
out-of-order superscalar pipelines. As a result, on any modern CPU
(including all mobile CPUs) a linear search outperforms almost any other
searching algorithm for surprisingly large Array sizes!
Given that stream IDs are intrinsically sorted, and thus all
per-stream-data is intrinsically sorted by stream ID, we have the
ability to use either of the above strategies. More importantly for us,
we have the ability to be _adaptive_ to those strategies, and swap
between them as needed.
Thus we deploy the StreamMap. This data structure stores per-stream data
in a pair of circular buffers, keyed by stream ID. For smallish numbers
of streams we just search these buffers linearly. For larger numbers, we
flip over to binary search.
Why circular buffers? Because we avoid a compaction problem. While in
general removal of stream IDs is done in arbitrary order, in _general_
the mostly likely streams to end at any given time are the oldest and
the youngest. Circular buffers make removing streams at those ends very
cheap, as compaction can be done easily. This, along with avoiding new
allocations, makes circular buffers a perfect data structure for this
strategy.
Modifications:
- Implemented StreamMap
- Replaced Dictionary
Results:
Meaningful performance gains on all benchmarks. 1k requests with 1
concurrent stream sees about a .1% performance improvement. 1k requests
with 100 concurrent streams sees a more like 15% performance
improvement.
Co-authored-by: George Barnett <gbarnett@apple.com>
Motivation:
Heap allocations that aren't necessary for program correctness are to be
avoided.
Modifications:
- Avoid heap allocating for constructing indirect enum cases.
Result:
Fewer heap allocations.
Resolves#255.
Reduces instructions executed in cachegrind server-only benchmarks by
about 0.15%.
Reduces icache miss rate by 3% in cachegrind due to reduced jumps to
cold malloc code.
Motivation:
Without knowing where an error was thrown it can be unnecessarily
difficult to work out the reasons an application ended up in an error
state.
Modifications:
- Add a 'file' string to each of the 'NIOHTTP2Errors' denoting the file
and line where an error was created
- Add static methods to create errors to 'NIOHTTP2Errors' defaulting
file and line, this is unfortunately necessary as defaulting file and
line in the `init` makes the defaulted and non-defaulted errors
indistinguishable, and the compiler will pick the one with fewest
defaulted values.
- Add equatable conformance manually so as to ignore 'file'
- Add backing storage to errors which no longer be stored in an existential
container
- Add 'CustomStringConvertible' conformance to the errors using backing
storage so that the 'file' is actually visible when converting the
error
- Deprecate the old `init`s
- Fix all deprecation warnings
Result:
- NIOHTTP2Errors carry a 'file' with them indicating where they were
created
Motivation:
The 2 to 1 codecs do a number of operations where they "peek" the
pseudo-headers. Each of these operations uses the HPACKHeaders
subscript, meaning that they allocate a temporary array for a field that
can, in a correct request/response, contain only one element. That's
very wasteful!
Modifications:
- Rewrite peekPseudoHeader to iterate instead, avoiding the array.
- Add allocaton counter test.
Result:
4 fewer allocations per HTTP request transformed on the server side,
2 fewer allocations per HTTP response transformed on the client side.
Motivation:
Unnecessary allocations are bad!
Modifications:
- Use 'removeAll' instead of allocating a new buffer when dropping
pending reads in the 'HTTP2StreamChannel'
- Use a static empty buffer in 'DataBuffer.evacuatePendingWrites'
Result:
- Fewer allocations.
- Resolves#240
- Resolves#241
Motivation:
As part of the work done for #214 we made `HTTP2StreamChannel` generic
over the type of data it reads and writes. Unfortunately this cost us a
non-trivial amount of performance.
Modifications:
- Remove the genericism from 'HTTP2StreamChannel' by adding a mode for the
stream data type the channel is operating on (frames or frame
payloads), wrapping and unwrapping the data where necessary.
- Simplify the implementation of 'MultiplexerAbstractChannel'
- Remove 'HTTP2FrameConvertible' since it is no longer required
Result:
A perf win, hopefully.
Motivation:
NIOHTTP2WindowUpdatedEvent was larger than 24 bytes, forcing heap
allocations whenever we wanted to put it into an existential. Given that
the range of the two optional integers stored on the type are both
explicitly documented to be the Int32 range, this type can happily just
contain Int32s.
Modifications:
- Changed the backing storage from Int? to Int32?.
Result:
NIOHTTP2WindowUpdatedEvent will be smaller.
Motivation:
In an earlier patch (1e68e51) we attempted to avoid emitting
WINDOW_UPDATE frames on streams that were already closed on their
inbound side. This was largely a reasonable fix, but we missed an
important area: END_STREAM in a sequence of frames.
This would be triggered if we received multiple DATA frames in a row,
where the last one contained END_STREAM but an earlier one triggered a
WINDOW_UPDATE. The stream state machine would have seen the END_STREAM
already and will forbid the WINDOW_UPDATE, but the stream channel won't
yet have seen it and will try to send it.
The fix is easy enough: look for END_STREAM earlier.
Modifications:
- Check for END_STREAM when the stream channel receives the frame, not
when it passes it into the pipeline.
Result:
Fewer spurious connection errors.
Motivation:
In some cases it's possible for a stream to emit a WINDOW_UPDATE frame
after receiving close from the network. This is unfortunate because in
the eyes of the `NIOHTTP2Handler` the stream no longer exists which
results in a connection-level error.
Modifications:
- Add a `close()` to the `InboundWindowManager`, no new frame sizes will
be produced if close has been called
- Use the above functionality when the stream is closing and when we
have seen end stream.
Result:
WINDOW_UPDATE frames are no longer emitted from the stream as a result
of delivering pending reads while closing.
Motivation:
NIO's backpressure management systems rely on catching calls to read()
in the ChannelPipeline. This only works if your Channel implementation
actually makes those calls to read()! Sadly, HTTP2StreamChannel did not:
we instead just recursed directly into the Channel's read0().
While I'm here I also noticed that we produced a lot of
channelReadComplete messages in the pipeline unnecessarily. We did this
in the service of having a read "fast-path" where new frames would be
automatically delivered into the ChannelPipeline without being buffered
until channelReadComplete. This fast-path is probably inadvisable: I
don't think it provided a meaningful performance benefit anyway,
especially as the removal of that fast-path allowed us to suppress
unnecessary calls to channelReadComplete, and therefore unnecessary
calls to read() as well.
Modifications:
- Forced autoRead through the pipeline.
- Removed read() fast-path.
- Suppressed channelReadComplete if no frames were delivered.
- Updated tests.
Result:
Clearer I/O path, better auto-read handling.