184 Commits
Author SHA1 Message Date
Cory Benfield d4060ac4d0 Make HPACKHeaders inlinable. (#269)
Motivation:

HPACKHeaders is a trivial data structure (a wrapper around Array) that
is present in the public API of all NIO HTTP/2 programs. This makes it a
tempting target for adding inlinable calls, primarily as a way to drive
down ARC. The fact that strings frequently travel across the API
boundary means that otherwise innocuous use-cases can trigger unexpected
ARC traffic.

Making as much of the implementation inlinable as possible reduces a lot
of this overhead and opens up the possibility for better performance in
a number of parts of the code, including in the core HTTP/2 protocol
engine, which operates extensively on this data type.

Modifications:

- Make basically everything inlinable.

Result:

Our benchmarks are about 0.7% faster.
2020-12-08 09:46:30 +00:00
Cory Benfield d3fece353d Remove some generics that were triggering ARC (#270)
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.
2020-12-04 19:38:04 +00:00
Cory Benfield 1dd123a849 Reduce ARC in HPACK closestMatch (#268)
Motivation:

When analysing remaining performance cliffs, we observed that
HeaderTableStorage.closestMatch was the source of a surprising amount of
ARC traffic. Further diagnosis revealed that we were ARCing string
storage as we iterated the table. Given that the table is constructed of
String/String pairs, the effect would be that if we scanned a table we
would emit two retains and two releases for each entry. Whenever we
encode a HTTP/2 header that we think could be indexed, we will scan the
static and possibly the dynamic tables to find a header that matches.
This ends up being a pretty nasty performance cost, as swift_retain and
swift_release are particularly complex on Strings, and often have
trouble with cache coherency and cache misses.

This got root-caused to https://bugs.swift.org/browse/SR-13931.

Modifications:

- Work around SR-13931 by avoiding using the iterator.
- While we're here, remove generics as well, as we aren't using them.

Results:

4% perf gain in 10k requests 100 concurrent streams benchmark and
10k requests 1 concurrent streams benchmark.
2020-12-04 09:43:24 +00:00
Cory Benfield f4b49cbed1 Partially revert #263. (#267)
Motivation:

In #263 we took advantage of the addition of the
unsafeUninitializedCapacity:initializingWith constructor on String,
added in the latest Swift SDKs and Swift versions.

Unfortunately, there were a few Xcode releases that shipped with Swift
5.3 but _without_ the macOS 11 SDK. These releases therefore had a 5.3
compiler, but no access to the macOS 11 SDK where the constructor is
defined.

This means this change regressed builds on those platforms.

Modifications:

Removed access to the fast-path initializer on Apple platforms in 5.3.
The initializer is present and will continue to work on non-Apple
platforms. Apple platforms will get access to that initializer from 5.4
onwards.

Result:

Fewer build issues for users using Xcode 12.0 and 12.1.
2020-12-03 14:00:16 +00:00
Cory Benfield 46b6e0197c Micro-optimise checked arithmetic in huffman. (#266)
Motivation:

Huffman decoding has rapidly become one of the most expensive parts of
the program. Some of the code here is unavoidably expensive, but there
is some unnecessary checked arithmetic here on offset. Removing that
provides a small but meaningful improvement to the performance of this
function.

Modifications:

- Remove the checked arithmetic on offset, which is bounded by a
   previous operation that was already checked.

Result:

This function gets cheaper by about 4%, though the benchmark as a whole
only sees a 0.1% improvement.
2020-12-03 12:03:41 +00:00
Cory Benfield 37919ba1b7 Reduce the cost of flushing (#265)
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.
2020-12-03 11:00:25 +00:00
Cory Benfield 2f3c6e7423 Cheaper calculation of flushes. (#264)
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%).
2020-11-30 17:51:47 +00:00
Cory Benfield c61955a870 Use proper String unsafeUninitializedCapacity initializer. (#263)
Motivation:

A while ago we shimmed out the String unsafeUninitializedCapacity
initializer because while it was on the road to being implemented, it
hadn't actually been implemented. Now it has!

On Apple platforms, the initializer is guarded behind an availability
guard. We need to add that guard here. This means we need to keep hold
of the backport for a good long time, until we raise our minimum Apple
platform support to a new enough version. Happily, Linux on 5.3 should
just see a net win here.

Modifications:

- Updated to enable us to use the proper initializer.

Result:

Fewer allocations when screwing around with HPACK.
2020-11-28 15:56:31 +00:00
Cory Benfield 57976bcc1d Improve bulk stream teardown. (#261)
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.
2020-11-26 09:18:46 +00:00
Cory Benfield ec1fad4c07 Move the huffman benchmark base64 out of init (#262)
Motivation:

The init() of all benchmarks will execute, even when we filter a
benchmark run down to a single benchmark. We should avoid doing heavy
work there, because it can confuse us when we look at traces elsewhere.

Modifications:

- Move some heavy work in the huffman benchmark base64 decode out of
  init().
- Prevent setUp() and tearDown() from running if a test is filtered out.
- Avoid even creating benchmarks unless they're filtered in.

Result:

Less confusing benchmark traces.
2020-11-26 08:43:13 +00:00
Cory Benfield 3315a639de Add benchmark and alloc test for GOAWAY teardown. (#260)
Motivation:

We don't have any benchmarks or alloc counter tests for doing stream
teardown with GOAWAY frames. While this isn't a terribly hot code path
and isn't terribly performance heavy with allocations, it's good to have
more data here.

Modifications:

- Write benchmarks and alloc counter tests that tear down many streams
  with GOAWAY.

Result:

Better testing and alloc counter.
2020-11-24 17:24:42 +00:00
George Barnett 7774067c43 Add properties to HTTP2StreamID to determine stream initiator (#259)
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?'
2020-11-24 14:41:26 +00:00
Cory BenfieldandGeorge Barnett a08dce89a6 Implement StreamMap and replace Dictionary (#258)
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>
2020-11-24 12:57:37 +00:00
Cory Benfield 7435b8446f Reduce allocations in OutboundFlowControlBuffer. (#257)
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.
2020-11-19 14:00:15 +00:00
Cory Benfield 54f15a6b16 Add benchmarks and improve benchmarking. (#256)
Motivation:

Performance benchmarking wants accurate numbers, and a wide range of
possible benchmarks. One way to get somewhat more accurate numbers is to
use a tool like Cachegrind to measure the instruction counts of a
program. Cachegrind allows us to isolate a number of noise-introducing
effects, as "number of executed instructions" is a much more stable
number than how long a program takes to run.

When running under cachegrind we want to change the way our performance
benchmarks work. Instead of running lots of times to try to average out
noise, we only want to run once to save ourselves time, as the benchmark
itself should be drastically more stable.

While we're here, let's add some much more isolated benchmarks than our
current "make lots of streams" benchmark. This is basically the same
logic, but it does less of NIO and so makes the impact of NIOHTTP2
substantially more prominent.

Modifications:

- Added a cachegrind build mode to the benchmarks.
- Added new benchmarks and alloc counters.

Result:

More info
2020-11-19 11:09:09 +00:00
George Barnett 94c35c6c45 Fix 'heder' typo (#252)
Motivation:

- Typos are bugs. Bugs are bad.

Modifications:

- s/heder/header

Result:

Fewer typos
2020-10-26 11:12:31 +00:00
George Barnett 440d64d99a Add a location to each of 'NIOHTTP2Errors' (#247)
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
2020-09-24 15:21:58 +01:00
Cory Benfield 5b0194aa63 Reduce allocations when peeking pseudo-headers. (#246)
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.
2020-09-24 09:57:47 +01:00
George Barnett cee48fd87d Remove a few unnecessary allocations. (#243)
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
2020-09-22 11:17:19 +01:00
George Barnett 860a6e77c8 Make HTTP2StreamChannel non-generic (#242)
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.
2020-09-22 11:04:11 +01:00
Cory Benfield 869fcd1bba Shrink NIOHTTP2WindowUpdatedEvent. (#239)
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.
2020-09-18 11:29:45 +01:00
Cory Benfield c7ad256b3e Move END_STREAM check earlier. (#237)
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.
2020-09-10 09:07:04 +01:00
Cory BenfieldandGeorge Barnett 7d366b1b77 Remove needless branch, clean up variable names. (#234)
Motivation:

No point having conditional branches when the branch is always taken!
This doesn't hurt perf at all, the optimiser will trivially see through
this, but it does hurt readability. Relatedly, the single-letter
variable names here aren't great.

Modifications:

- Removed needless branch.
- Gave the variables better names.

Result:

Easier to understand code.

Co-authored-by: George Barnett <gbarnett@apple.com>
2020-08-28 09:38:43 +01:00
George Barnett 1e68e51752 Avoid emitting WINDOW_UPDATE frames when receiving stream closed (#233)
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.
2020-08-24 15:13:19 +01:00
George Barnett 9f4eff0603 Bring HPACKHeaders function parity closer to HTTPHeaders (#232)
Motivation:

HTTPHeaders and HPACKHeaders have very similar APIs, yet some of the
functionality of HTTPHeaders is missing from HPACKHeaders.

Modifications:

- Add `remove`, `replaceOrAdd`, `capacity` and `reserveCapacity` to
  HPACKHeaders

Result:

- HPACKHeaders is closer in feature parity to HTTPHeaders
2020-08-20 11:19:39 +01:00
Cory Benfield d87661d4e8 Propagate read() through the pipeline. (#231)
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.
2020-08-13 15:01:52 +01:00
George Barnett e9627350bd Verify payload-based stream channel fixes #214 (#228)
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.
2020-08-05 10:19:05 +01:00
George Barnett 38afdfce3e Deprecate the HTTP2 to HTTP1 codecs (#227)
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
2020-08-04 14:25:28 +01:00
George Barnett 177c50a566 Add new pipeline helpers and deprecate old paths (#226)
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
2020-08-04 12:52:00 +01:00
George Barnett b03b4e8a2d Multiplexer tests for payload-based stream channels (#225)
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`
2020-08-03 16:29:17 +01:00
George BarnettandCory Benfield 98a86c5df4 Allow payload-based stream channels to be created. (#221)
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>
2020-08-03 11:21:21 +01:00
George Barnett 3c668f5c7e Add HTTP2Frame.FramePayload codecs (#222)
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.
2020-07-31 10:29:42 +01:00
George BarnettandCory Benfield cde820ed39 Make HTTP2StreamChannel generic over a message type (#218)
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>
2020-07-29 13:04:53 +01:00
Cory Benfield 04706e7df5 Refactor the codecs for extension. (#219)
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.
2020-07-29 09:26:49 +01:00
Cory Benfield edd373d96c Update HTTP2StreamChannel to tolerate nil stream ID. (#217)
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.
2020-07-28 16:19:38 +01:00
Cory Benfield 125cab766c Define abstraction for multiplexer holding channel. (#215)
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.
2020-07-28 14:48:46 +01:00
George Barnett 7b0faab2de Add HTTP2FrameConvertible and HTTP2FramePayloadConvertible (#216)
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.
2020-07-28 14:16:19 +01:00
Cory Benfield c8f952dbc3 Respect target window size on inbound channels. (#205)
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.
2020-06-01 09:29:36 +01:00
Cory Benfield b66a08e4bc Add debugging info to HTTP2StreamChannel too. (#198)
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.
2020-05-11 13:28:56 +01:00
Cory Benfield 5f665cd9e2 Make HTTP2StreamChannel.isActive thread safe (#199)
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
2020-05-11 12:44:32 +01:00
John KassebaumandCory Benfield 0ca9705831 Make multiplexer's targetWindowSize configurable and use configurability when creating stream channels. (#202)
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>
2020-05-11 12:34:43 +01:00
Cory Benfield 32db4dd7c2 Swap Huffman unnecessary var to let. (#203) 2020-05-11 11:49:17 +01:00
Cory Benfield 271b5570e8 Improve debugging output for HTTP2Handler. (#197)
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.
2020-04-28 14:11:17 +01:00
Jon Shier 82eb3fa097 Make replacement method public, clean up ACLs. (#194) 2020-03-21 08:13:55 +00:00
Mario SangiorgioandCory Benfield 798c19b86e Added helper to configure HTTP1 or H2 accordingly to the negotiated protocol (#193)
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>
2020-03-17 14:34:32 +00:00
George Barnett fbfe24ccee Exert backpressure via stream flow control windows (#191)
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.
2020-03-12 07:45:00 +00:00
Johannes Weiss 65ebab9db7 stream channel initialiser: allow closed & failed (#183)
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
2020-02-11 13:03:41 +00:00
Johannes Weiss c1bfb7ce3f fix new NIO and new Swift compiler warnings (#179) 2019-12-10 12:45:48 +00:00
Eric York 859f6b46aa Issue #151 Update BadStreamStateTransition to have stream state (#175)
Update BadStreamStateTransition to have an enum NIOHTTP2StreamState that shows which state the stream was in before the error.
2019-12-09 09:56:41 +00:00
George Barnett a8f89aa368 Add a subscript to HPACKHeaders to return the first value with a matc… (#178)
* Add a subscript to HPACKHeaders to return the first value with a matching name

Motivation:

In some cases you only expect (or care about) a single value for a
header. However, getting this value without allocating an array or
traversing the whole array requres using first(where:) provided by
Sequence. This is not very ergonomic as it requires users to do the
case-insensitive comparison and then exctact the value from the
HPACKHeader. Additionally, users cannot use NIO HTTP/2s case insensitive
ASCII comparison.

Modifications:

- Provide a first(name:) method on HPACKHeaders which returns the value
  from the first header whose name is a case insentive match of the
  subscript parameter.

Result:

It's easier to get the first
2019-12-04 12:07:31 +00:00