68 Commits
Author SHA1 Message Date
George Barnett 61f6aa4142 Add explicit Sendable annotations (#505) 2025-03-27 14:01:05 +00:00
Gus Cairo 170f4ca06b Don't fail closeFuture when an error occurs on closing (#487)
Strictly speaking, a `close` operation can't really fail (except when
the closing mode isn't supported or the channel is already closed). Even
if an error is encountered while closing a channel, or if an error
caused the channel to be closed, the end result is the same: the channel
will be closed.

In this case in particular, when streams are closed from the client
(i.e. by sending a RST_STREAM frame) the `HTTP2StreamChannel` would fail
the channel's `closeFuture`. This isn't appropriate however, as the
channel is successfully closed.

This change stops failing the stream channel's `closeFuture`. Instead,
if the close happens uncleanly, the error will be fired down the
pipeline and the `close` method's promise will be failed.
2024-12-16 15:38:34 +00:00
Peter Adams 1118370ec4 Apply swift-format changes and CI (#472)
Motivation:

Standardised formatting makes the project cleaner to look at and work
on.

Modifications:

Setup swift-format with the same settings as Swift-NIO

Result:

Common formatting throughout
2024-10-29 13:09:54 +00:00
George Barnett ab04d05c6f Reduce allocs in HTTP2StreamChannel (#449)
Motivation:

The HTTP2StreamChannel stores two atomic booleans for whether the
channel is active and writable. These are only accessed externally and
access is relatively infrequent. Each atomic requires an allocation,
instead we can just protect each with a single lock.

Modifications:

- Combine the two atomics into a single 'flags' struct protected by a
  locked value box

Result:

Fewer allocations
2024-07-18 01:13:16 -07:00
George Barnett ac2a15cc88 Keep capacity when dropping pending reads in the stream channel (#447)
Motivation:

When the stream channel has closed it drops all of its pending reads. It
does this by calling 'removeAll()' on its CircularBuffer. The buffers
underlying storage is emptied and then a `nil` is appended (internally
CircularBuffer is never empty) which triggers an allocation.

Modifications:

- Remove all but keep capacity

Result:

Fewer allocations
2024-07-08 09:26:51 +01:00
George Barnett ed8a315489 Reduce error allocations (#446)
Motivation:

Existential errors are unconditionally boxed. We typically create and
use errors to fail promises when performing cleanup work. One example
of this is failing pending writes when a stream channel is closed,
however this is done unconditionally which means every stream channel
incurs an allocation when it closes.

Modifications:

- Statically create some existential errors ahead of time

Result:

Fewer allocations
2024-07-05 08:35:46 -04: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 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
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 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 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 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
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
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
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
Cory Benfield cb6f87d9e0 Use Docc for documentation (#351)
Motivation

Documentation is nice, and we can help support users by providing useful
clear docs.

Modifications

Add Docc to 5.6 and later builds
Make sure symbol references work
Add overview docs

Result

Nice rendering docs
2022-08-09 06:44:21 +01:00
David Nadoba f9ab1c94c8 Use swift-atomics instead of NIOAtomics (#350)
`NIOAtomics` was deprecated in https://github.com/apple/swift-nio/pull/2204 in favor of `swift-atomics` https://github.com/apple/swift-atomics
2022-07-11 16:11:50 +01:00
David Evans c13f959b10 Adopt Sendable in relevant types (#343)
* Implement Sendable

* Make structs Sendable

* Update HTTP2Error.swift

* Fix compile

* Fix compile (again)

* Remove weird imports

* Cleanup

* Cory PR comments

* Remove Sendable conformance from Errors

* Cleanup

* Cleanup

* Remove unused concurrency import

* Remove NIOSendable from HTTP2Error.swift

* Cleanup

* Revert changes in HTTP2Error
2022-05-06 11:50:26 +01:00
Fabian Fett 39ed0e7535 Forward all reads before stream channel inactive (#317)
### Motivation

In the AsyncHTTPClient the read event is not always forwarded right away. We have seen instances, in which we see a `HTTPClientError.remoteConnectionClosed` error, on requests that finish normally. https://github.com/swift-server/async-http-client/issues/488 

On deeper inspection, I noticed: If there is no unsatisfied read event, when a stream is closed, the pending reads are not forwarded. This can lead to response bytes being ignored on successful requests. NIOHTTP2 should behave as NIO and force forward all pending reads on channelInactive.

### Changes

- Forward all pending reads on channelInactive even if no read event has hit the channel

### Result

All requests will receive the complete request body.
2021-11-30 18:24:42 +01:00
Cory Benfield f0adfc1d6d Deliver outbound stream errors to channels. (#315)
Motivation:

When we hit a stream error on an outbound frame, we don't currently
distinguish between them and channel errors. This makes it impossible
for anyone to tell them apart. It also makes it impossible for the
multiplexer to deliver these errors into the relevant stream channels
that triggered them, making it essentially certain they'll be lost.

Better diagnostics would be good, so we are providing them.

Modifications:

- Add new StreamError type that carries a stream ID and an underlying
  error.
- Emit this StreamError type for outbound stream errors.
- Deliver this StreamError type into the relevant child channels when
  possible.

Result:

Better diagnostics for stream errors.
2021-11-26 17:38:36 +00:00
Cory Benfield dbfc8fcd1a Clean up imports and dependencies. (#300)
Motivation:

With NIO 2.32.0 we broke the core NIO module up into modules that split
apart the POSIX layer and the core abstractions. As a result, this
package no longer needs to express a hard dependency on the POSIX layer.

Modifications:

- Rewrote imports of NIO to NIOCore.
- Added NIOEmbedded imports where necessary in tests.
- Note that the main modules still depend on NIO, which is necessary
    for backwards-compatibility reasons. This dependency is unused.

Result:

No need to use NIOPosix.
2021-09-14 11:30:04 +01:00
Fabian Fett 42bdcae4ac Use non-deprecated API for removing handlers (#297)
### Motivation:

`removeHandlers(channel:)` was deprecated in NIO 2.32.0.

### Modifications:

- Raise minimum required `NIO` version to 2.32.0
- Use `removeHandlers(pipeline:)`

### Result:

We don't use deprecated API.
2021-08-18 16:22:51 +02:00
George Barnett e7af0132c8 Use sync options when creating a stream channel (#283)
Motivation:

SwiftNIO 2.27.0 added synchronous channel options. We can use these if
available when creating a stream channel to avoid a future allocation.

Modifications:

- 'getAutoReadFromParent' is synchronous when possible and now takes a
  closure to handle the result.
- Update allocation counts (and sort them to make updating them easier,
  this also includes switching the order we run test_1k_requests
  interleaved and noninterleaved)

Result:

Fewer allocations.
2021-03-16 10:10:00 +00:00
George Barnett 4e96d02e0e Add sync option support to HTTP2StreamChannel (#282)
Motivation:

SwiftNIO 2.27.0 added support for synchronous channel options allowing
callers to get options synchronously -- saving a future allocation -- if
they know they're on the correct event loop. 'HTTP2StreamChannel' should
support this.

Modifications:

- Add 'HTTP2StreamChannel.SynchronousOptions' with conformance to
  'NIOSynchronousChannelOptions'

Result:

Callers can get and set options synchronously on 'HTTP2StreamChannel'
2021-03-16 08:38:35 +00:00
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