42 Commits
Author SHA1 Message Date
George Barnett 0c99c555c5 Avoid unnecessary futures in stream creation (#271)
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
2021-01-14 17:14:17 +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
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 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
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
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 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 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 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 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
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
Johannes Weiss 994c319e03 namespace ChannelOptions & fix deprecations (#166) 2019-10-28 16:11:12 +00:00
Cory Benfield 492a77b186 Support child channel writability management. (#142)
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.
2019-07-19 16:49:22 +01:00
Cory Benfield 06880b0abd Minimise channelReadComplete traffic. (#136)
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.
2019-06-18 11:54:43 +01:00
Cory Benfield 0d153b56a4 Coalesce flushes during the read cycle. (#132)
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.
2019-05-24 18:38:34 +01:00
Cory Benfield 2d5ab32f23 Remove indirection between channel and multiplexer (#126)
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.
2019-05-17 18:58:08 +01:00
Cory Benfield 6ab190327d Better manage stream channel activation. (#124)
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.
2019-05-17 14:15:56 +01:00
Cory Benfield 1a82080f1b Allow closing idle StreamChannels. (#123)
* 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.
2019-05-16 15:39:45 +01:00
Cory Benfield f1cc1f5069 Replace Future with a function call. (#116)
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.
2019-05-16 15:17:19 +01:00
Cory Benfield 016bf0be4d Avoid 2 heap allocations on child channel creation (#115)
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.
2019-05-16 14:57:52 +01:00
Cory Benfield 55daa4cd4e Correctly notify StreamMultiplexer of SETTINGS changes. (#67)
Motivation:

The StreamMultiplexer and StreamChannels are responsible for sending
WINDOW_UPDATE frames, but they were never told if the user changed the
value of SETTINGS_INITIAL_WINDOW_SIZE. They should be.

Modifications:

- Send user events when SETTINGS_INITIAL_WINDOW_SIZE changes.
- Use those window events to change the target window size in
    HTTP2StreamChannel.
- Keep track of the last stream window size we knew.

Result:

Less chance of flow control mess.
2019-03-15 17:37:00 +00:00
Cory Benfield 3c90345c36 Pure-Swift HTTP/2 implementation (#40)
* Updated to use SwiftNIO 1.10+ to gain access to HTTPHeaders internals.

* Add pure-Swift HTTP/2 protocol implementation.

Motivation:

Currently we use nghttp2 for our basic protocol implementation. This is
plenty workable, but provides us a number of limitations. It adds
complexity to our build system, provides us with external dependencies we
have little control over, limits our users' ability to express low-level
protocol semantics if they so wish, causes us to heap-allocate like crazy over
the lifetime of a connection, and brings a world of pain around reentrancy.

This set of limitations has motivated a desire to move away from using
nghttp2. This is a part of that dream.

Modifications:

- Add pure Swift protocol implementations.
- Test them.

Results:

Another step towards protocol independence.

* Initial basic parser code.

* Adding unit tests.

* Add NIOHTTP2FlowControlHandler

Motivation:

One of the things that nghttp2 used to do for us was to handle buffering
DATA frames until flow control allowed them to go out. For users that
want that behaviour, we need to replace the nghttp2 code with a new
ChannelHandler that can do this work.

Modifications:

- Added NIOHTTP2FlowControlHandler.

Result:

Users will have the same feature set as they did with nghttp2.

* Generate Linux test information.

* Documentation comment.

* Updated new tests from master to use new payload types.

* Updated following review.

Notable changes:

- Implemented unit tests for the ALTSVC (0xa) and ORIGIN (0xc) frame types.
- Additional DATA frames are synthesized to wrap individual payload chunks as they arrive. If the payload of a DATA frame with 4MB data arrives in 4 separate 1MB chunks, the decoder will emit 4 DATA frames, with only the last containing the END_STREAM flag (if that was set on the incoming frame).
- HEADERS / PUSH_PROMISE frames and any following CONTINUATION frames are now handled properly: header fragments from all frames are gathered up into a single buffer. Once a frame with END_HEADERS is encountered, the resultant accumulated buffer is sent for decoding along with the flags and stream ID of the original HEADERS / PUSH_PROMISE frame.
- HPACK encoders/decoders now live in the frame encoder/decoder types, rather than being attached to a stream.

* Updated Linux tests.

* Headers placed in relevant files.

* Add pure-Swift HTTP/2 protocol implementation.

Motivation:

Currently we use nghttp2 for our basic protocol implementation. This is
plenty workable, but provides us a number of limitations. It adds
complexity to our build system, provides us with external dependencies we
have little control over, limits our users' ability to express low-level
protocol semantics if they so wish, causes us to heap-allocate like crazy over
the lifetime of a connection, and brings a world of pain around reentrancy.

This set of limitations has motivated a desire to move away from using
nghttp2. This is a part of that dream.

Modifications:

- Add pure Swift protocol implementations.
- Test them.

Results:

Another step towards protocol independence.

* Revamped frame decoder state machine and API. Now uses separate input and output methods to manage multiple frames in a single buffer.

* Updated Linux tests.

* Bumped swift-nio version to 1.12.0 and updated `HTTPHeaders` -> `HPACKHeaders` conversion initializer to directly copy the buffer and map the header name/value indices.

* Set up HTTP2Parser in handlerAdded if the channel had been previously activated. (#36)

By setting up the handler in the handlerAdded hook, HTTP2Parser supports
being added dynamically in a channelRead event, after the channel has sent
the channelActive event.

(cherry picked from commit 88bd6d369a)

* Minor tweaks to get the tests passing

* Initial integration here

* Minor clearing up of the handler

* Get the tests compiling

* Fix header issues.

We now pass the frame parser to the various setting operations to let it
update the state. We also fixed some issues with specific settings.

* Remove ngthttp2-based impl, clean up stream ID

* Tests with new HTTP2StreamID

* Simple test cleanup

* Get remaining non-core tests passing

* Allow GOAWAY even when fully quiesced

* We don't buffer outbound frames any more

* Emit StreamClosed events on GoAway frame

* Notify stream creation and closure

* This test started failing

* Goodbye, C code! 🎉

* Send PING ACK automatically

* Updated based on PR feedback.

* Correctly handle 1XX responses

* Add SETTINGS_MAX_FRAME_SIZE support to flow controller

* Correctly account for flow control

* Define ConcurrentStreamsHandler

* Prepare for signalling connection state changes

* Better state change message propagation

* Refactor to use result with effect everywhere

* Don't lose flow control info on stream error

* Add basic flow control management to stream multiplexer

* Better pipeline in sample server

* Clean up some reentrancy concerns

* Move to Swift 5 and NIO 2

* Move to new Swift 5 for CI

* Allow wider range of choices of years

* Catch up to NIO 2 again
2019-02-21 11:52:49 +00:00
Cory Benfield 38b8235868 Correctly activate child channels. (#27)
Motivation:

Child channels should not activate before their parents.

Modifications:

Delay activation if the parent channel is not currently active.
Activate during channelActive, if needed.

Result:

Easier to start HTTP/2 requests
2018-11-26 11:44:53 +00:00
Cory Benfield d17462f586 Fix example server.
Motivation:

The example server had slowly bitrotted over time: some minor fixes were
needed.

Modifications:

I fixed it!

Result:

The example server works against a basic curl command.
2018-05-18 17:53:21 +01:00
Cory Benfield aee602c435 Add interface for creating channels from the client side. (#6)
Motivation:

While the HTTP2StreamMultiplexer could create channels in response to
inbound request streams on the server side, there was no interface for
creating channels locally.

That would make having a HTTP/2 client kinda tricky!

Modifications:

Added HTTP2StreamMultiplexer.createStreamChannel.

Result:

Possible to write HTTP/2 clients.
2018-05-18 17:26:12 +01:00
Cory Benfield 0a271b1cef Remove handlers from stream channel pipelines on shutdown. (#5)
Motivation:

When closing a stream channel, it must remove its channel handlers.

Modifications:

Call ChannelCore.removeHandlers on shutdown.

Result:

Handlers are removed on channel shutdown.
2018-05-18 14:05:12 +01:00
Cory Benfield e2ea2b88b9 Support read() 2018-05-17 11:58:25 +01:00
Cory Benfield bbcb593a6d Support buffered writes 2018-05-16 17:53:26 +01:00
Cory Benfield 5c5987e6ad Manage delayed stream channel setup 2018-05-16 15:37:41 +01:00
Cory Benfield 87cfe4897f Test stream-initiated closure. 2018-05-16 14:24:22 +01:00
Cory Benfield 59611cd174 Initial multiplexer testing 2018-05-15 17:36:43 +01:00
Cory Benfield 4acc76bfd7 Fire user events when streams are closed 2018-05-14 17:57:10 +01:00
Cory Benfield c937029ad4 Remove CONTINUATION (and so endHeaders).
We treat CONTINUATION frames as an implementation detail, which means the
endStream flag is also redundant. Let's remove both.
2018-05-03 10:48:54 +01:00
Cory Benfield 1ef32a0d3d Correct handling of stream IDs. 2018-04-27 15:40:18 +01:00
Cory Benfield 2044c89450 Improve HTTP2StreamChannel state handling.
Motivation:

The HTTP2StreamChannel needs to be aware of the HTTP/2 state machine,
at least at some level. This is to ensure it can map that state
machine onto the (unfortunately implicit) NIO stream state machine
and appropriately clean up resources like stream promises.

Modifications:

Lots. Added stream state tracking, refactored the frame structure,
stopped creating stream 0 as a sub-stream, and more.

Result:

We no longer crash when the curl TCP connection goes away.
2018-04-23 17:15:17 +01:00
Cory Benfield df69a91f18 Add stream ID channel option 2018-04-18 18:20:28 +01:00
Cory Benfield bab2bb7cfc Removed debugging handlers 2018-04-18 16:28:12 +01:00
Johannes Weiß 504c24939e very rough first steps towards the first handled HTTP/2 request 2018-04-11 15:06:12 +01:00