Motivation:
We made a bunch of changes to resolve#214. We should add a test to
ensure we actually fixed the issue.
Modifications:
- Add a test verifying that we can write on streams in a different order
to the order in which we create them
- Add a corresponding test for frame-based streams verifying that the
first write on each stream must match the order in which the streams
were created
- Remove an unnecessary `throws` in the base HTTP2 to HTTP1 server codec
Result:
- No functionality change, just more tests.
Motivation:
We added HTTP2FramePayload-to-HTTP1 codecs as part of #214 but are yet
to deprecate their HTTP2-to-HTTP1 counterparts.
Modifications:
- Deprecate `HTTP2ToHTTP1ClientCodec`
- Deprecate `HTTP2ToHTTP1ServerCodec`
- Deprecate tests containing them
- (We already have tests for HTTP2FramePayload-to-HTTP1 codecs)
Result:
HTTP2-to-HTTP1 codecs are deprecated
Motivation:
As part of #214 we need to introduce new pipeline helpers to configure
the channel pipeline with the new handlers. This PR adds those helpers
and deprecates the old paths.
Modifications:
- Add pipeline helpers with the new streamID-less initializer
- Switch old pipeline helpers which provided codecs to use the new path
and codecs
- Duplicate SimpleClientServerTests and ConfiguringPipelineTests to add
frame payload based counterparts
- Deprecate older helpers and multiplexer init, delete tests which don't
hit deprecated paths (note: these still exist in the payload based
counterparts)
- Update Bench1Conn10kRequests to be payload based
Result:
- More 'FramePayload' based Tests
- Paths for creating an 'HTTP2Frame' based stream via
'HTTP2StreamMultiplexer' are now deprecated
Motivation:
As part of #214 we added a stream channel which deals with
`HTTP2Frame.FramePayload` as well as the relevant entry points in
`HTTP2StreamMultiplexer` to create these streams. We didn't add a
corresponding set of tests.
Modifications:
- Duplicate `HTTP2StreamMultiplexerTests`
- Refactor to make use of new stream creation function and new inbound
stream initializer
- Fix up a couple of bugs in `HTTP2StreamMultiplexer`:
- activate pending streams on `channelActive`
- deactivate pending streams on `channelInactive`
- change stream writability for pending streams on `channelWritabilityChanged`
- add implementation for `childChannelClosed(channelID:)`
Result:
- Tests for payload-based stream creation via `HTTP2StreamMultiplexer`
Motivation:
To lift the requirement that stream creation order must match the order
of the first write on those channels we added a payload-based stream
channel. We need a way for users to create these channels and initialze
these channels when they are inbound.
Modifications:
- Adds a `createStreamChannel` using a stream initialzer without a
stream ID
- Adds a new multiplexer `init` where the inbound stream initialzer does
not use stream IDs
- Adds an additional 'configure' to MultiplexerAbstractChannel
- Replaces the `init` in `MultiplexerAbstractChannel` with two `static func`s:
we can't switch on an optional stream ID since inbound streams always
have a stream ID; we need to be be able to explicitly support choosing
the type of channel we want.
- Minor refactoring in `HTTP2StreamChannel` to avoid duplication between the
`configure` functions
Result:
- The multiplexer can create payload based streams manually and when a
new stream is inbound.
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
As part of the work for #214 we need new codecs which transform
`HTTP2Frame.FramePayload` to and from the appropriate request and
response parts.
Modifications:
- Add `HTTP2FramePayloadToHTTP1ClientCodec`
- Add `HTTP2FramePayloadToHTTP1ServerCodec`
- Duplicate the HTTP2ToHTTP1CodecTests and update the relevant parts to
use payloads instead of frames.
- Add relevant test helpers.
- Note: the HTTP2 to HTTP1 (frame based) codecs haven't been deprecated:
doing so without warnings depends on #221.
Result:
- We can transform `HTTP2Frame.FramePayload` types to the relevant HTTP
client and server request and response types.
Motivation:
As part of #214 we need to make `HTTP2StreamChannel` generic over the type
of message it expects to read and write. This allows us to define an
`HTTP2StreamChannel` which uses `HTTP2Frame.FramePayload` as its
currency type, rather than `HTTP2Frame`.
Modifications:
- Make `HTTP2StreamChannel` generic over `Message` which is constrained
by conformance to `HTTP2FrameConvertible` and
`HTTP2FramePayloadConvertible`
- `HTTP2StreamChannel` now expects to read in `Message`s (as opposed to
`HTTP2Frame`s) and have `Message`s written in to it.
- Added typealiases for frame and payload based stream channels.
- Added support for the payload based channel in
`MultiplexerAbstractChannel` (although one can't be created yet).
Result:
We can create payload based stream channels.
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
As part of the work in #214 we're going to need to update the
HTTP2ToHTTP1 codecs. These need to be replaced for the new channel
pipelines. The core of the logic will be identical in both cases, so
let's start by factoring that logic out into some nice standalone
objects that we can reuse.
Modifications:
- Pull out the base codecs into structures.
- Rewrite the main codecs in terms of these new structures.
Result:
Easier extension points.
Motivation:
As part of the work in #214, HTTP2StreamID will need to be able to
tolerate not knowing its stream ID. For now this is not a problem, but
we should think about everywhere we use the stream ID and make sure we
have a solid principle in mind. This lays the groundwork for future
enhancements.
Modifications:
- Update HTTP2StreamChannel to hold an optional stream ID.
- Update interface to HTTP2StreamMultiplexer to tolerate closing
channels without stream IDs (we'll need it later).
- Move the "get a new stream ID" functionality to a method on
HTTP2StreamMultiplexer.
- Validate we behave correctly with optional stream IDs in the channel.
Result:
We can tolerate stream IDs being not present.
Motivation:
As part of the work in #214 we need a way for the HTTP2StreamMultiplexer
to hold multiple kinds of channels. It would be best if doing so didn't
require substantial changes to HTTP2StreamMultiplexer, which is
difficult because right now it is tightly coupled to HTTP2StreamChannel.
There are a few ways we could do this. The most obvious option to most
Swift programmers would be to define a protocol that covers the surface
area we want to use, and then hold that. This works fairly well, but the
downside of it is that it will force all calls from
HTTP2StreamMultiplexer to become dynamically dispatched. These indirect
calls are optimisation boundaries and so provide some performance costs.
Another option would be to create a subclassing relationship. This is
ok, but it also forces us into the realm of dynamic dispatch on some of
these calls, and also provides general difficulty if we ever want to
provide a backing channel that isn't easily made into a subclass.
The remaining option is to provide an abstract object that uses an
`enum` to store the kinds of channel we know about, and jump through it.
This works really well for small numbers of channel types (1 and 2
channels being the best outcomes), as it introduces very few extra
branches which are highly predictable, as well as allowing direct
function calls. This is great: one predictable branch that cannot
possibly miss cache, followed by a direct function call. Joy of joys!
However, it would be best if we didn't tie ourselves into this
implementation strategy. After all, down the road we could well end up
with more kinds of channels, and at a certain point the cost of the
indirect function call becomes _lower_ than the cost of jumping through
the enumeration. For that reason, we should define an abstraction.
Enter: `MultiplexerAbstractChannel`. This concrete type defines the
interface that `HTTP2StreamMultiplexer` will use to interact with stream
channels. As it's internal, the abstraction is totally porous: Swift is
capable of optimising it away to nothing. This type is explicitly a
reference type, maintaining the semantic expected by
`HTTP2StreamMultiplexer`.
This provides a nice encapsulation over our abstraction.
`HTTP2StreamMultiplexer` never needs to know about how we abstract over
multiple channel types: the entire abstraction lives in a single, simple
file, and can easily be rewritten without difficulty.
Modifications:
- Define `MultiplexerAbstractChannel` and the interface expected by
`HTTP2StreamMultiplexer`.
- Define a `BaseChannel` `enum` that will be used to dispatch to
multiple `Channel` types.
- Rewrite `HTTP2StreamMultiplexer` to use this new abstraction.
Result:
A customisation point for new channels will exist.
Motivation:
As part of the work for #214 to enforce stream creation order we need to
remove the requirement that the data sent over the stream be aware of
its stream ID ahead of time. This requires that the channel transporting
the data provide the stream ID. As such we need a way to convert between
data with stream IDs and data without stream IDs.
Modifications:
- Add 'HTTP2FrameConvertible' protocol whose conforming types can make
an 'HTTP2Frame'.
- Add 'HTTP2FramePayloadConvertible' protocol whose conforming types can make
an 'HTTP2Frame.FramePayload'.
- Conform 'HTTP2Frame' and 'HTTP2Frame.FramePayload' to the above
protocols.
Result:
We have a protocol which an HTTP2 stream channel may be generic over.
Motivation:
As part of #202 we added support for configuring the target window size
of stream channels. That was plumbed through into outbound channels, but
we missed the inbound ones, meaning that this only really worked for
clients, not servers. That hardly seems fair!
Modifications:
Pass target window size to inbound channels too.
Result:
We can control target window size of inbound channels.
Motivation:
Sometimes folks will want to print things about the HTTP2StreamChannel,
and we should give them the things we can safely get. We also may want a
shorter log for NIOHTTP2Handler as the standard description, with the
wall of text available in the debug description.
Modifications:
- Conform HTTP2StreamChannel to CustomStringConvertible
- Conform NIOHTTP2Handler to CustomDebugStringConvertible.
Result:
Even better debug info.
Motivation:
All public parts of the Channel protocol, such as isActive, are required
to be thread safe. Unfortunately, we missed a spot with the isActive
bool on HTTP2StreamChannel.
Modifications:
Back the HTTP2StreamChannel.isActive bool with an atomic, and set it on
state change.
Result:
Thread-safety for public readers of channel activity
Motivation:
Infow target window size constrains throughput. The default hardcoded 65535 is low for some use cases and so needs to be configrable. A TODO in the code stated 'Make configurable'.
Modifications:
- In HTTP2StreamMultiplexer, responding to a TODO where stream multiplexer creates a stream channel, created a multiplexr stored property to be used which is set in the default initilaizer.
- In HTTP2PipelineHelpers, added versions of configureHTTP2Pipeline(..) and configureCommonHTTP2ServerPipeline that require an activeTargetWindow arg.
Result:
Clients, such as GRPCClient, can configure pipelines with targetWindowSizes to their liking.
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
Sometimes it's useful to be able to print out objects and see their
internal state. Somehow, HTTP2Handler can't do this.
Modifications:
Add a conformance to HTTP2Handler.
Result:
Awesome debugging output.
Motivation:
Applications might want to support H2 (when available) and HTTP1 (as a fallback).
The application logic should not change between the two versions of the protocol
and the code to configure support for both the protocols is boilerplate and can
be provided as an helper function.
Modifications:
This PR adds an helper function to configure HTTP1 or H2 pipelines according to
the protocol negotiated by the TLS handler.
Result:
Applications that need to support clients using both HTTP1 and H2 can
configure their channels by calling `configureCommonHTTPServerPipeline`,
which should reduce the boilerplate they have to write.
Co-Authored-By: Cory Benfield <lukasa@apple.com>
Motivation:
When a window update event is received in the stream channel we notify
the inbound window manager. Doing so may emit a WINDOW_UPDATE frame
to indicate the remote may send us more DATA. However, this happens even
if there are inbound frames waiting to be delivered to the channel. This
may lead to the remote sending us more DATA which we have to buffer
until it is read.
Modifications:
- Update the inbound window manager to track the number of bytes
buffered in the stream channel
- Account for buffered bytes when receiving a new window size event
- Possibly emit WINDOW_UPDATE after unbuffering inbound frames into the
stream channel's pipeline
Result:
The timing of WINDOW_UPDATE frames is better aligned with when frames
are actually read in a stream.
Motivation:
Previously, if we failed in the stream channel initialiser and the
stream channel was closed before finishing the stream channel
initialiser, we would crash on an assertion because `closedWhileOpen`
correctly asserted that it has nothing to do and shouldn't be called.
Modification:
Apart from `.idle` also stop calling `closedWhileOpen` in `.closed` and
`.localActive` because the network actually doesn't think this channel
is open.
Result:
- Fewer crashes
- fixes rdar://59342916
Motivation:
Frames that close a stream may consume some of the connection window. We
were not correctly accounting for that in the code, which meant that
frames that carried END_STREAM would not notify the stream multiplexer
that they had consumed connection window space. In the worst cases this
could lead to resource starvation due to consumption of this window
without causing us to emit new WINDOW_UPDATE frames.
Modifications:
StreamClosedEvents should be followed by flow control change events.
Result:
We will correctly update the connection window when a stream is closed.
Motivation:
The HTTP/2 RFC does not explicitly forbid sending more than one
RST_STREAM for the same stream. Given that we have seen this behaviour
in the wild we are going to ignore any additional RST_STREAMs.
A further indicative that this is the right call is that the RFC
explicitly mentions that sending RST_STREAMs in the idle state is not
acceptable.
Modifications:
Ignore RST_STREAM frames for streams in the closed state.
Result:
More compatibility.
Motivation:
HTTP/2 is mostly just HTTP(/1) semantics with streams on a new wire
protocol. However, there are certain things that are legal in HTTP/1 but
which are illegal in HTTP/2.
Modification:
Accept more of those messages and transform them into their HTTP/2
equivalent.
Result:
- Easier to write HTTP/2 clients & servers in NIO.
- fixes#152
* Forbid excessive sending of empty DATA frames
Motivation:
One vector for DoS can be sending a large number of essentially "empty"
frames, such as empty DATA frames without END_STREAM set. We should
forbid peers from doing so excessively, but we want to tolerate
implementations that occasionally emit such a frame for buggy reasons.
Modifications:
- Added verification that too many empty DATA frames are not sent.
Result:
Better resistance to DoS attacks.
* Improved buffering in CompoundOutboundBuffer
Motivation:
In HTTP/2 it is possible for remote peers to submit work in a way that
cause the NIOHTTP2Handler to generate a substantial number of control
frames. If the peer is not consuming these frames, we can eventually run
out of memory and die, which is not exactly ideal.
It's hard for us to know how the buffering is going if we always submit
all frames directly to the Channel, so we need to pay attention to
whether the Channel is actually writable. If it isn't, rather than issue
further writes we need to delay those writes so we can keep track of how
big that buffer is getting. If the buffer gets too large we need a
circuit breaker to drop the connection, as we're clearly not able to get
work done.
This patch adds a new buffer for outbound control frames. This new
buffer is the last step in the buffering sequence, and the first to be
drained when a Channel becomes writable.
Additionally, enhancements need to be made to ensure that other buffers
behave correctly in the face of this new model. The
ConcurrentStreamsBuffer needs to be more aggressive about storing
HEADERS frames that cannot be emitted to the wire because it does not
tolerate emitting a HEADERS frame that cannot be immediately written to
the wire. Additionally, the buffers must not be polled when a Channel is
unwritable.
This is a large patch, but it does substantially change the buffering
logic, and protects NIO against a wide range of denial of service
attacks, while providing a clear and coherent defense surface.
Note that one thing this patch does not do is constrain the size of the
buffers in the ConcurrentStreamsBuffer. This is on purpose: the size of
this buffer is controlled entirely by user action. Users that do not
wish to buffer excessively in this buffer can avoid doing so simply by
respecting the peer's value of SETTINGS_MAX_CONCURRENT_STREAMS. As the
entire purpose of this buffer is to tolerate users that do not wish to
abide by this setting, it would be unreasonable to provide an upper
bound on the value used in this setting.
Modifications:
- Moved the various buffers into a directory.
- Built and implemented ControlFrameBuffer.
- Integrated ControlFrameBuffer into CompoundOutboundBuffer.
- Added awareness around channel writability to HTTP2Handler
- Enhanced ConcurrentStreamsBuffer to be writability-aware.
Result:
We'll have somewhere to put control frames.
* Cleanup API for merged security fixes.
Motivation:
After merging the security fixes we ended up with a slightly awkward
API: the argument names differed slightly for no good reason, and it
became impossible to override only one of the two security settings.
Modifications:
- Renamed `max` to `maximum`.
- Gave default values for the security settings.
Result:
Better user experience.
* Prevent DoS with large header lists.
Motivation:
There are two ways malicious peers could attempt to DoS a SwiftNIO
HTTP/2 implementation with header lists. The first would be to attempt
to send an enormous header list, ideally with an amplification factor.
This approach was possible because SwiftNIO never actually enforced the
value of the max header list size it advertised.
In principle the peer can still get a good amplification attack effect
by sending a long header list that contains zero-length headers. We may
as well close this door as well: zero length header field names are
unacceptable, and so we should forbid them.
Modifications:
- Added max header list enforcement.
- Forbade zero-length header field names.
Result:
Peers cannot DoS a SwiftNIO HTTP/2 implementation using large header
lists.
Motivation:
It's important to ensure that child channel users can observe the
writability state of a child channel in order to avoid ballooning data
in memory. Up until now we haven't supported writability notifications,
but we really should.
Modifications:
- Added a flow controller to manage writability.
- Managed data flow through promises.
- Lots of tests.
Result:
Child channels will provide a much better signal as to whether they are
writable.
Motivation:
Previously, the H2to1 codec would crash if for example a push promise
came by.
Modifications:
Instead of crashing, ignore the frames without equivalent.
Result:
Fewer crashes.
Motivation:
RFC 7540 is not particularly clear on whether the server is required to
send PUSH_PROMISE frames before or after the HEADERS frame, or whether
both are acceptable. We took a somewhat hard-line approach by asserting
that PUSH_PROMISE could only be sent after the server sent HEADERS, but
we've now caught at least one notable implementation in the wild doing
something different (nghttp2).
Given that there's no clear normative language pointing in either
direction, we should consider being a bit more lenient and allowing
both.
Modifications:
- Updated the stream state machine to allow pushes on a locally-idle
stream.
Result:
Servers can send PUSH_PROMISE before they have sent HEADERS.
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.