229 Commits
Author SHA1 Message Date
George Barnett 8d8eb60992 Add a variant of configureAsyncHTTP2Pipeline which takes a stream delegate (#439)
Motivation:

`configureAsyncHTTP2Pipeline` doesn't allow a stream delegate to be
specified. As the async pipeline uses the "inline" stream multiplexer
there's no way to account for streams within the connection channel.

Modifications:

- Add a sync and async variants of `configureAsyncHTTP2Pipeline` which
  accepts an optional stream delegate
- Rewrite the existing helpers in terms of the new one

Result:

Users can configure an async http pipeline with a stream delegate.
2024-05-16 14:12:57 +01:00
Johannes Weiss 356a3af761 test compiler not language version (#440) 2024-05-09 12:59:05 +01:00
Stefana-Ioana Dranca c6afe04165 Avoid CoW while processing the next state when HTTP2FrameDecoder decodes (#438)
Motivation:

CoWs appear when switching over the current state of the parser and holding it while also modifying it - inside `processNExtState()`. Following `append(bytes: ByteBuffer)`'s pattern, we should use a function that sets the state to an intermediary one with no associated data, before making the transformations.

Modifications:
- created the `avoidParserCoW()` helper function for the throwing functions
- used it in the switch cases inside `processNextState()`

Result:

CoW will be avoided when changing the state of the HTTP2FrameDecoder when decoding, so we won't have unnecessary heap allocations.
2024-04-17 09:08:28 +01:00
taylorswift (dianna) 75c10ea32e Update documentation for configureAsyncHTTPServerPipeline (#435) 2024-02-27 09:07:58 +00:00
Rick Newton-RogersandCory Benfield 69e838fb22 Remove precondition: yielding to terminated AsyncSequence (#432)
Motivation:

If a task iterating over inbound streams using the new async API is
cancelled then it can lead to the process crashing as we hit a
precondition which guards against yielding to a terminated
NIOHTTP2AsyncSequence.

Modifications:

Remove the precondition.

Result:

The code no longer crashes, instead it silently drops the yielded value.

Doing more than this such as closing the connection requires rethinking
more of the API.

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2023-12-20 14:57:41 +00:00
Rick Newton-Rogers 285e444b49 Sendability warnings (#417)
Motivation:

To address warnings revealed with
`.enableExperimentalFeature("StrictConcurrency=complete"),` in Swift 5.8

Modifications:

* Numerous protections of state in tests
* Make the multiplexer instances explicitly loop bound
* Update channel initializers to be marked as Sendable
* Mark error backing storage types as unchecked sendable

Result:

Better thread safety
2023-11-01 14:36:38 +00:00
Rick Newton-Rogers a6c66bcbe7 Mark public generic async methods inlinable (#426)
* Mark generic async methods inlinable

Motivation:

Mark generic async methods inlinable where possible to improve performance.

Modifications:

Multiple methods marked `@inlinable`

Result:

Performance increase
2023-10-30 09:29:37 +00:00
Rick Newton-Rogers 462ded73ad HTTP/2 Async API (#424)
We previously developed an async API for NIO HTTP/2 which was guarded under SPI. Now that the swift-nio async API is released we can reintroduce this code promoted to SPI.

This change introduces:
* `AsyncStreamMultiplexer` - an async variant of the HTTP/2 stream multiplexer which can be used to create outbound streams and provide access to an async sequence (`NIOHTTP2AsyncSequence`) of inbound streams
* New pipeline configuration functions (e.g. `configureAsyncHTTP2Pipeline`) to support the new async mode
2023-10-25 15:49:16 +01:00
Rick Newton-Rogers d6f9a3b90d Bump minimum Swift version to 5.7 (#420)
* Bump minimum Swift version to 5.7

Motivation:

Now that Swift 5.9 is GM we should update the supported versions and
remove 5.6

Modifications:

* Update `Package.swift`
* Remove `#if swift(>=5.7)` guards
* Delete the 5.6 docker compose file and make a 5.10 one
* Update 5.10 alloc limits
* Update docs

Result:

Remove support for Swift 5.6, add 5.10
2023-10-11 00:12:29 -07:00
Rick Newton-Rogers 9c22e4f810 DOSHeuristics DeadlineClock more explicit on 5.6 (#422)
Motivation:

The type inference system isn't able to work out the default clock type
in the DOSHeuristics init on Swift 5.6 so this change makes it more explicit

Modifications:

Add more explicit inits

Result:

The code should build on 5.6 and later
2023-10-10 18:11:34 +01:00
Rick Newton-Rogers 3798fe5f15 Merge pull request from GHSA-qppj-fm5r-hxr3
* Limit rate of permitted RST frames

Motivation:

Large number of stream reset frames may be used as a DoS (Denial of
Service) vector in an attempt to overload the CPU of the handling server.

Modifications:

Introduce an additional DoS heuristic which evaluates the rate of
incoming stream reset frames. If the rate exceeds that which is
permitted then the connection is closed and a `GOAWAY` issued.

The allowed rate is configurable but defaults to 200 resets within 30
seconds. This should be acceptable for most applications.

Result:

Excessive reset frames result in the connection being closed.

* review comments

* further review comments

* add integration test
2023-10-10 13:00:57 +01:00
Rick Newton-Rogers 2140160e95 Remove dependency on SPI (#419)
Motivation:

Remove dependency on SPI so that we can cut a release without
introducing dependency on code subject to change.

Modifications:

Remove all code which introduces a dependency on the NIOAsyncChannel SPI

Result:

Code inside SPI is removed
2023-10-04 13:21:17 +01:00
Rick Newton-Rogers 8275314739 Async stream initializers order matches existing (#415)
Motivation:

When adding in the SPI methods for exposing async sequences of HTTP/2
streams we moved the stream initialization to a subtly different
location so that it was easier to exfiltrate the outputs of those
initialization functions (such as protocol negotiation outputs).

In some cases this broke ordering expectations.

Modifications:

Yield the (optionally wrapped) channels as initializer outputs to the async stream

Result:

Changes only exist within SPI. Async inbound stream channel
initialization now matches previous behavior.
2023-09-11 14:46:40 +01:00
George Barnett 92afa4fa84 Delay stream creation until the next loop tick (#416)
Motivation:

A recent change allowed stream creation to run immediately if the caller
was on the correct event loop. Normally that's fine, however, it opens
up a code path where streams can become activated twice which leads to a
crash.

Modifications:

- Delay stream creation until the next loop tick
- Add a loop tick to tests which now require it

Result:

Avoid re-entrantly activating streams twice.
2023-08-23 11:28:07 +01:00
Si Beaumont 2bf57336ec Update to latest NIO with updated protocol negotiation SPI (#414)
* Update to latest NIO with updated protocol negotiation API

Signed-off-by: Si Beaumont <beaumont@apple.com>

* fixup: Also replace deprecated get().waitForFinalResult()

Signed-off-by: Si Beaumont <beaumont@apple.com>

---------

Signed-off-by: Si Beaumont <beaumont@apple.com>
2023-08-08 14:36:51 +01:00
Quirin Schweigert 493897c474 Fix parent channel read() call on HTTP2StreamChannel initialization causing incorrect order of inbound HTTP2Frames (#413)
Motivation:

Make sure the order of `HTTP2Frame`s that are fired through the pipeline of a `HTTP2StreamChannel` by `HTTP2CommonInboundStreamMultiplexer` is correct when a `read()` call on the parent channel synchronously causes further frames to be processed.

Modifications:

Reorder calls in `HTTP2CommonInboundStreamMultiplexer.receivedFrame(frame:context:multiplexer)` so that initial header frame is buffered and processed first.

Result:

Resolves #410 and makes newly added test case `HTTP2StreamMultiplexerTests.testMultiplexerFiresInitialFramesInCorrectOrder()` pass.
2023-07-28 09:15:01 +01:00
Franz Busch 7e4dd147b0 Adopt latest AsyncChannel changes (#411)
# Motivation
In my latest PR in NIO, I removed a bunch of API from the bootstrap methods to make the API easier to digest and reduce a number of duplicated code issues.

# Modification
This PR adopts the latest NIO changes and adapts the APIs in H2. More specifically, it removes the `NIOAsyncChannel` convenience methods and makes sure that everything aligns nicely with the proposes bootstrap APIs.

# Result
We now have the APIs in place to bootstrap a protocol negotiated H1/H2 server.
2023-07-26 13:48:25 +01:00
Rick Newton-Rogers 044339de7b HTTP/2 negotiated connection pipeline config (#408)
Motivation:

This continues the work to expose functionality which allows users to interact
with HTTP/2 connections via async abstractions and using structured
concurrency.

This work enables protocol negotiation between HTTP/1.1 and HTTP/2 in its most generic form.

Modifications:

Enable protocol negotiation between HTTP/1.1 and HTTP/2 using typed
negotiation results (`NIOProtocolNegotiationResult`) from the
`NIOTypedApplicationProtocolNegotiationHandler`.
In the HTTP/2 case the negotiation result will return the HTTP/2 connection
channel and the `NIOHTTP2Handler.AsyncStreamMultiplexer` which exposes
inbound streams as an iterable async stream.

Result:

Users will be able to set up negotiated HTTP/1.1 / HTTP/2 connections and
iterate over inbound streams.
2023-07-12 11:07:53 +01:00
Rick Newton-Rogers 188fa9ba27 adopt NIOAsyncChannel.Configuration (#409)
Adopt NIOAsyncChannel.Configuration as the NIO SPI changed
2023-07-11 16:43:41 +01:00
Rick Newton-Rogers d5f0715865 Tweak formatting of function DocC comments (#407)
Motivation:

Tweaking the formatting of the DocC comments enables syntax highlighting
for parameter names in Xcode

Modifications:

Whitespace changes, capitalisation changes and added a parameter
description for `indexing` in HOACKHeaders `replaceOrAdd`, `add`.

Result:

More readable DocC comments
2023-07-05 05:35:47 -07:00
Rick Newton-Rogers 6e35856efa Add additional NIOAsyncChannel config (#406)
* Add additional NIOAsyncChannel config

Motivation:

Recent additions to pipeline configuration did not expose some of the
`NIOAsyncChannel` configuration.

Modifications:

Expose `backpressureStrategy`, `isOutboundHalfClosureEnabled`.

I think specific naming and object encapsulation for these parameters should be discussed
later before SPI is removed and we review the API as a whole.

Result:

Pipelie helpers for `NIOAsyncChannel` expose `backpressureStrategy`, `isOutboundHalfClosureEnabled`.

* review comments, re-order parameters

* review comments

* param reordering, missing docs comments
2023-07-04 17:24:08 +01:00
Rick Newton-Rogers f6f43195a2 H2 stream AsyncIterator non-sendable on 5.7 (#405)
Motivation:

Marking `NIOHTTP2InboundStreamChannels.AsyncIterator` as non-sendable
fails to compile on 5.6 however implicitly non-sendable will do, this is
a nice-to-have.

Modifications:

Move the non-sendable annotation to only apply >= 5.7

Result:

`NIOHTTP2InboundStreamChannels.AsyncIterator` is implicitly non-sendable
on 5.6
2023-07-04 11:09:40 +01:00
Rick Newton-RogersandGeorge Barnett e0ffed790a HTTP/2 pipeline NIOAsyncChannel pipeline config (#403)
* HTTP/2 pipeline NIOAsyncChannel pipeline config

Motivation:

This continues the work to expose functionality which allows users to interact
with HTTP/2 connections via async abstractions and using structured
concurrency.

We build atop of previous work to configure pipelines to deal with
HTTP/2 (with no protocol negotiation) and to wrap connection/stream
channels with `NIOAsyncChannel`s. This will allow users to iterate over
streams and HTTP2Frames.

Modifications:

Provide functions which configure channels and pipelines with the HTTP2
handler, expose a multiplexer for dealing with streams and wrap
connection and stream channels with `NIOAsyncChannel`s.

Result:

Users will be able to create and interact with HTTP/2 connections via
`NIOAsyncChannel`s. Because HTTP/2 is a negotiated protocol and we do
not yet handle it, this is of limited utility.

* review comments

* Update Sources/NIOHTTP2/HTTP2ChannelHandler+InlineStreamMultiplexer.swift

Co-authored-by: George Barnett <gbarnett@apple.com>

---------

Co-authored-by: George Barnett <gbarnett@apple.com>
2023-07-04 06:21:57 +01:00
Rick Newton-Rogers b9fe8f57a0 Inline http2 fixups (#402)
There are a few places where bugs / poorly structured code crept in during the inline multiplexer work. This attempts to address some of them:

- overly long lines
- mis-named variables
- unnecessary use of generics in one case
2023-07-03 03:54:55 -07:00
Rick Newton-Rogers 83c04dbddb Generic helpers for HTTP/2 async pipelines (#401)
* Store HTTP/2 inbound streams as async sequence

Motivation:

In preparation for exposing APIs which surface HTTP/2 connections and
streams using structured concurrency this PR introduces a store for
inbound HTTP/2 streams.

Modifications:

Define types and methods for storing generic types which wrap `Channels`
corresponding to inbound HTTP/2 streams in an async sequence.

Result:

The new types are not yet exposed, this work introduces part of the
framework for future functionality.

* Expose (as spi) helpers for H2 async pipelines

Motivation:

This PR is the first step in exposing APIs which surface HTTP/2 connections and
streams using structured concurrency. This PR exposes the most abstract
spelling of this concept, assuming no particular types/forms for the
types involved in the stream channel types.

Modifications:

* Store a generic `streamInitializer` on the common inbound initializer
  which is used to initialize inbound streams before yielding them to
the continuation of streams.
* Expose pipeline configuration functions which assume HTTP/2 but
  nothing else about sream channel types.
* Provide internal functions for creating streams without configuring
  them. Configuring leads to activation so it can be helpful to allow
that step to be performed manually once any provided initialization
closures have beenn executed.

Result:

Adopters of the new SPI should be able to create outbound and deal with
inbound HTTP/2 stream channels using async streams.

Outside of SPI there should be no changes.
2023-07-03 11:19:04 +01:00
Rick Newton-Rogers fc2e98ecad use synchronous H2 multiplexer accessor (#396)
* use synchronous H2 multiplexer accessor

Motivation:

The `ChannelPipeline.SynchronousOperations.configureHTTP2Pipeline(...)`
method added to support synchronously setting up a pipeline to handle HTTP2 with the `StreamMultiplexer` embedded within the `NIOHTTP2Handler` erroneously retrieved the multiplexer via a `.wait()`. This is not permitted and will cause any code which executes it to deadlock.

Modifications:

The synchrounous operation now obtains the multiplexer via
`handler.syncMultiplexer()`

Result:

The code should not deadlock.

* update allocation counts
2023-05-30 11:19:37 +01:00
Rick Newton-Rogers ec955b609b Inline multiplexer calls writability mgr directly (#386)
Motivation:

The `HTTP2StreamChannel` keeps track of how many bytes have been written
and how many are buffered for use in evaluating the 'writability' of the
stream channel. Bytes are considered 'written' or at least no longer
buffered when the write is completed (successfully or errored). In order to make the
determination of when writes are complete across channel handlers we attach a promise to all
writes and deduct adjust the byte counts on completion. Creating and
attaching these promises requires costly allocations.

Modifications:

We can remove the need to create these promises for the new inline
stream multiplexer because the multiplexer and man HTTP2 channel
operations are now all within the `HTTP2ChannelHandler`. This change
calls the `writabilityManager` directly when writes are completed.

Result:

* Fewer allocations are required for HTTP2 writes.
* Writes are considered 'complete' when they leave the `HTTP2ChannelHandler`
2023-04-11 16:40:37 +01:00
Cory Benfield 81b001dd07 Add regression testing for docs and fix the issues. (#389) 2023-04-11 11:04:31 +02:00
Rick Newton-Rogers 12fcce2ec8 flowControlledSize only counts DATA frames (#388)
Motivation:

HTTP2 flow control only cares about DATA frame sizes so we can be more
accurate and drop the complexity of `flowControlledSize`

Modifications:

`flowControlledSize only returns non-zero sizes for `DATA` frames

Result:

`flowControlledSize only returns non-zero sizes for `DATA` frames
2023-04-06 09:15:04 -07:00
Rick Newton-Rogers 7f82cc3d64 Replace estimatedFrameSize with flowControlledSize (#387)
Motivation:

`estimatedFrameSize` aims to estimate the number of bytes a frame will
use on the wire. It includes the 9-octed frame header and is currently
used for flow control estimates but according to spec it shouldn't
include those 9 bytes https://www.rfc-editor.org/rfc/rfc9113.html#section-6.9.1

Modifications:

Replace `estimatedFrameSize` with `flowControlledSize` which ignores the
9-octed frame header and update tests.

Result:

Flow control calculations should be more accurate
2023-04-06 15:08:11 +01:00
George Barnett d22e5ea2e5 Avoid allocation in outbound frame buffer (#385)
Motivation:

CiruclarBuffer always allocates on init as it never has a zero capacity.
It is implemented in such a way that changing this is not trivial. The
compound outbound buffer creates a marked circular buffer
unconditionally on each call but only uses it if there are streams to
drop.

Modifications:

Add a static empty marked circular buffer to the compound outbound
buffer and rely on CoW semantics to avoid the allocation for each call
in cases where there are no frames to drop.

Result:

Fewer allocations.
2023-04-06 11:30:14 +01:00
Rick Newton-Rogers 78176ba277 Remove NIOHTTP2StreamDelegate Sendable requirement (#384)
Motivation:

Remove `NIOHTTP2StreamDelegate` `Sendable` conformance requirement.
This wasn't needed in the first place because `NIOHTTP2Handler`
is not `Sendable`, therefore it never leaves the thread on which it is
created.

The delegate may still be `Sendable` depending on the implementation
but it is not a strict requirement.

Modifications:

Remove NIOHTTP2StreamDelegate Sendable requirement

Result:

Sendable is no longer required for NIOHTTP2StreamDelegate conformance
2023-04-05 16:40:55 +01:00
Rick Newton-Rogers 795c1d4a48 Expose a functional NIOHTTP2StreamDelegate (#382)
Motivation:

Allow handlers in the pipeline to be notified when an HTTP2 stream is created or
closed.

Modifications:

Store an instance of a `NIOHTTP2StreamDelegate` on the `NIOHTTP2Handler`
and `InlineStreamMultiplexer` so that it may be called when streams are
created or closed.

Added tests.

Result:

`NIOHTTP2Handler`s init'd with a `streamDelegate` will now call into
that delegate's `streamCreated` and `streamClosed` functions.
2023-03-31 09:14:18 +01:00
Rick Newton-Rogers a32335d23e ChannelPipeline H2 inline multiplexer conf funcs (#381)
* ChannelPipeline H2 inline multiplexer conf funcs

Motivation:

To have parity with the legacy separate `HTTP2ChannelHandler`-`StreamMultiplexer` HTTP2 stream multiplexing model we provide channel pipelineconfiguration functions using the new inline multiplexer.

Modifications:

* New versions of `configureHTTP2Pipeline` and
  `configureCommonHTTPServerPipeline` which set up the pipeline using
inline stream multiplexers
* Tests targeting the new functions ported from
  `ConfiguringPipelineWithFramePayloadStreamsTests.swift`

Result:

New pipeline configuration conveniences for inline HTTP2 multiplexing
are available.
2023-03-30 17:34:13 +01:00
Rick Newton-Rogers befe813575 Implement direct stream (de)multiplexing in NIOHTTP2ChannelHandler (#380)
Motivation:

Less expensive stream multiplexing. To implement direct stream multiplexing (with an incomplete public API) to break up delivery and allow testing.

Modifications:

* Factor out common inbound stream multiplexer functionality from `HTTP2StreamMultiplexer` into `CommonInboundStreamMultiplexer` (first commit).
* Direct stream multiplexing is implemented as `InlineStreamMultiplexer`. It implements both the `HTTP2InboundStreamMultiplexer` and `HTTP2OutboundStreamMultiplexer` protocols.
* We expose `NIOHTTP2Hander.StreamMultiplexer` as a `public` view over the new multiplexer to allow stream creation.
* Adds various `propagate...` functions to relay signals such as read complete to the child channels held by the inline stream multiplexer.
* Adds a stub for `HTTP2StreamDelegate`  which will be completed in an upcoming PR. It will be responsible for surfacing stream open/close information.
* Adds conveniences to `NIOHTTP2Handler` for setting up a handler using the inline multiplexer
* Duplicate existing tests and modify to use the inline stream multiplexer where appropriate. `SimpleClientServerFramePayloadStreamTests.swift` and `HTTP2FramePayloadStreamMultiplexerTests.swift` were copied and modified

Result:

Default behavior should be unchanged at this time.
2023-03-30 15:45:20 +01:00
Rick Newton-Rogers 98170fdb0c Add multiplexer protocol abstraction in http2 stream channel (#379)
Motivation:

This change prepares for future work to embed the connection multiplexer within the `HTTP2ChannelHandler` which will improve performance by removing the need for passing expensive `InboundUserEvent`s.

Modifications:

This step defines a new protocol (`HTTP2StreamChannelMultiplexer`; named such to avoid confusion with the legacy handler, `HTTP2StreamMultiplexer`) which will later be used to abstract over the inline and legacy multiplexer code but at the moment should not change the logic.

Result:

Behaviour should be unchanged.
2023-03-06 05:49:13 -08:00
Rick Newton-Rogers 20d0634bcb Add no-op NIOHTTP2ConnectionDemultiplexer (#377)
* Add no-op NIOHTTP2ConnectionDemultiplexer

Motivation:

This change prepares for future work to embed the connection demultiplexer within the `HTTP2ChannelHandler` which will improve performance by removing the need for passing expensive `InboundUserEvent`s.

Modifications:

This first step defines a new protocol (`NIOHTTP2ConnectionDemultiplexer`) which will later be used to abstract over the embedded and legacy separate demultiplexer code but at the moment should not change the logic.

Result:

Behaviour should be unchanged.

* review comments

* no longer `nil` out demultiplexer on channelInactive
* restructure calling `pendingUserEvent` & processing events

* demultiplexer funcs use events, not components

NIOHTTP2ConnectionDemultiplexer stream  events now use event types
directly rather than individual parameters which map to the event
fields.
2023-03-06 03:06:42 -08:00
Cory Benfield 38feec96bc Soften errors when seeing inactive before active (#376)
Motivation:

When we started checking active/inactive ordering, we added code that
rejected some channel pipeline state transitions. That code was too
strict: it is absolutely possible to see channelInactive before
channelActive in well-functioning programs.

We'll still call this an error, but we don't need to crash in debug mode
when we see it.

Modifications:

- Made channelInactive before channelActive tolerated.

Result:

More reliable code
2023-03-02 13:34:42 +00:00
Cory Benfield 860622124b Correctly respect changes to HEADER_TABLE_SIZE (#374)
Motivation:

When remote peers set the value of HEADER_TABLE_SIZE to any non-default
value, or when we update it, we should respect that value when we're
emitting headers.

Unfortunately, right now we don't. In particular, we manage to update
the wrong setting: when the peer sets HEADER_TABLE_SIZE we bound the
maximum size of the dynamic table _they_ can use, not the maximum size
_we_ can use. That's incorrect by the spec, which says:

> This setting allows the sender to inform the remote endpoint of the
> maximum size of the compression table used to decode field blocks,
> in units of octets. The encoder can select any size equal to or less
> than this value by using signaling specific to the compression
> format inside a field block (see [COMPRESSION]).

If a peer sent us SETTINGS_HEADER_TABLE_SIZE with a value of 0, we'd
restrict _them_ to only using a maximum table size of 0, instead of us.
This is wrong.

Additionally, when we updated the encoder we used the wrong method, so
the encoder would never send dynamic table size changes. This was also
incorrect!

In general this managed to get missed because, as RFC 9113 notes:

> Implementers are advised that reducing the value of
> SETTINGS_HEADER_TABLE_SIZE is not widely interoperable. Use of the
> connection preface to reduce the value below the initial value of
> 4,096 is somewhat better supported, but this might fail with some
> implementations.

It turns out one of those implementations this might fail with is us!
The result, however, is that very few implementations actually try to
reduce the value of the header table size, so we rarely ran into this
issue. nginx does actually try this in some cases, however, which is how
we found this problem.

Modifications:

- Correctly invert the application of the value of
  SETTINGS_HEADER_TABLE_SIZE
- Correctly use `setDynamicTableSize` on HPACKEncoder instead of just
  setting the field manually.
- Deprecate the invalid method of setting the field on HPACKEncoder.
- Add some HTTP/2-level tests that ensure we correctly handle these
  changes.

Result:

Vastly better handling of peers reducing the value of
SETTINGS_HEADER_TABLE_SIZE.
2023-02-24 13:20:51 +00:00
Cory Benfield 8dcda68288 Ensure that we fire channelActive and channelInactive in order (#373)
Motivation:

channelActive must always precede channelInactive. Unfortunately, this
isn't guaranteed right now: if we happen to get channelInactive as a
result of our writing the preamble we'll fire them in the wrong order.
Many systems can tolerate this, but we should avoid doing this anyway.

Modifications:

- Added a state enum to keep track of the state we're in
- Use that state enum to ensure we deliver active/inactive in the right
  order
- Additionally police other unexpected active/inactive behaviours

Result:

We'll appropriately police the state.
2023-02-15 15:52:34 +00:00
George Barnett 5fcdf62ae8 Better handle writes issued with already completed promises (#372)
Motivation:

The stream channel updates its writability manager when issuing a write
to the parent channel and when the write promise has been succeeded.
If the write promise has already been succeeded then the writability
manager can be updated in the wrong order which can lead to underflow.

Modifications:

- Use signed arithmetic in the writability manager and allow pending
  bytes to become (briefly) negative.

Result:

The writability manager's pending bytes shouldn't underflow.
2023-02-10 17:16:48 +00:00
Cory Benfield 22757ac305 Content-Length errors shouldn't crash (#371)
Motivation:

When we added new content length verification and new errors, we didn't
update the places that were handling the old error. This code updates
that logic to ensure that we don't crash.

Modifications:

Add new internal protocol to which the content length validation errors
conform.
Catch that protocol instead.

Result:

No crashes on invalid content-length
2023-02-06 02:20:36 -08:00
b408ca74bf ContentLengthVerifier Update (#369)
Motivation:
Currently http2 ignores content length when handling a response to a HEAD request and handling a 304 response.

Modifications:
Changing ContentLengthVerifier and any functions called

---------

Co-authored-by: George Barnett <gbarnett@apple.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
2023-02-02 10:36:43 +00:00
Cory Benfield ac93134a8e Make FramePayload.Data class-backed (#365)
Motivation:

Using indirect cases makes unwrapping and rewrapping HTTP/2 frames more
expensive than it needs to be. As FramePayload.Data is essentially
always stuffed into a FramePayload enum, we may as well just class-back
it and avoid the extra allocs.

Modifications:

Make FramePayload.Data class-backed

Result:

Fewer allocations in many use-cases
2022-12-12 01:58:25 -08:00
George Barnett c7e4c5162f Provide an iterator for header values (#362)
Motivation:

We don't always require an array of header values to be extracted.
Sometimes we just need to be able to iterate through them. For 'regular'
header values we incur an allocation for the array, for values in their
canonical form we incure at least two allocations. We can do better than
this by providing a header value sequence.

Modifications:

- Add new API to `HPACKHeaders` for getting a sequence of header values
  which can optionally be in their canonical form.
- Update the API of the two existing subscripts to use this new API. For
  `subscript(canonicalForm:)` we save an allocation by not going via
  `subscript(name:)`.

Result:

- Fewer allocations in `subscript(canonicalForm:)`
- Header values can be iterated without allocating
2022-11-30 13:39:03 +00:00
Rick Newton-Rogers a6d0d37e2e ContentLengthVerifier init throws on negative values (#361)
Motivation:

We discovered that this code path can result in an arithmetic overflow
in the case where the content-length header has INT_MIN value. Since
negative content-lengths don't have any meaning anyway we may as well
throw if we encounter one so the decoding can be aborted.

Modifications:

* ContentLengthVerifier init throws a `ContentLengthHeaderNegative` error
when the decoded value is < 0.
* ContentLengthVerifier init throws a `ContentLengthHeaderMalformedValue` error
when the value cannot be decoded, e.g. it is out of bounds for Int or is
an invalid string.

Result:

We will no longer panic for INT_MIN content-lengths and will fail
decoding if one of various invalid values is encountered.
2022-11-25 13:41:46 +00:00
Rick Newton-Rogers b0b64afb0a ContentLengthVerifier checks all header vals match (#360) 2022-11-24 09:54:49 -08:00
carolinacass d6656967f3 Use #fileID/#filePath instead of #file (#359)
Motivation:

#fileID introduced in Swift 5.3, so no longer need to use #file anywhere

Modifications:

Changed #file to #filePath or #fileID depending on situation
2022-11-01 08:27:30 -07:00
George Barnett b1f1e68683 Replace NIOSendable with Sendable (#358)
Motivation:

NIOSendable was deprecated in https://github.com/apple/swift-nio/pull/2291
as the earliest supported Swift version in NIO land is now 5.5.

Modifications:

- s/NIOSendable/Sendable

Result:

Avoids deprecation warnings when the above patch is released.
2022-11-01 01:47:07 -07:00
David Nadoba a89ddbf0af Remove #if compiler(>=5.5) (#357) 2022-10-13 14:57:50 +01:00