mirror of
https://github.com/apple/swift-nio-http2
synced 2026-11-28 05:14:25 +00:00
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
This commit is contained in:
1 parent
d6f9a3b90d
commit
462ded73ad
6 files changed
+817
-3
No files matched your search
@@ -211,3 +211,42 @@ extension InlineStreamMultiplexer {
|
||||
self.commonStreamMultiplexer.setChannelContinuation(streamChannels)
|
||||
}
|
||||
}
|
||||
|
||||
extension NIOHTTP2Handler {
|
||||
/// A variant of `NIOHTTP2Handler.StreamMultiplexer` which creates a child channel for each HTTP/2 stream and
|
||||
/// provides access to inbound HTTP/2 streams.
|
||||
///
|
||||
/// In general in NIO applications it is helpful to consider each HTTP/2 stream as an
|
||||
/// independent stream of HTTP/2 frames. This multiplexer achieves this by creating a
|
||||
/// number of in-memory `HTTP2StreamChannel` objects, one for each stream. These operate
|
||||
/// on ``HTTP2Frame/FramePayload`` objects as their base communication
|
||||
/// atom, as opposed to the regular NIO `SelectableChannel` objects which use `ByteBuffer`
|
||||
/// and `IOData`.
|
||||
///
|
||||
/// Inbound (remotely-initiated) streams are accessible via the ``inbound`` property, having been initialized and
|
||||
/// returned as the `InboundStreamOutput` type.
|
||||
///
|
||||
/// You can open a stream by calling ``openStream(_:)``. Locally-initiated stream channel objects are initialized upon creation using the supplied `initializer` which returns a type
|
||||
/// `Output`. This type may be `HTTP2Frame` or changed to any other type.
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
public struct AsyncStreamMultiplexer<InboundStreamOutput> {
|
||||
private let inlineStreamMultiplexer: InlineStreamMultiplexer
|
||||
public let inbound: NIOHTTP2AsyncSequence<InboundStreamOutput>
|
||||
|
||||
// Cannot be created by users.
|
||||
internal init(_ inlineStreamMultiplexer: InlineStreamMultiplexer, continuation: any AnyContinuation, inboundStreamChannels: NIOHTTP2AsyncSequence<InboundStreamOutput>) {
|
||||
self.inlineStreamMultiplexer = inlineStreamMultiplexer
|
||||
self.inlineStreamMultiplexer.setChannelContinuation(continuation)
|
||||
self.inbound = inboundStreamChannels
|
||||
}
|
||||
|
||||
|
||||
/// Create a stream channel initialized with the provided closure
|
||||
/// - Parameter initializer: A closure that will be called upon the created stream which is responsible for
|
||||
/// initializing the stream's `Channel`.
|
||||
/// - Returns: The result of the `initializer`.
|
||||
public func openStream<Output: Sendable>(_ initializer: @escaping NIOChannelInitializerWithOutput<Output>) async throws -> Output {
|
||||
return try await self.inlineStreamMultiplexer.createStreamChannel(initializer).get()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1180,4 +1180,16 @@ extension NIOHTTP2Handler {
|
||||
throw NIOHTTP2Errors.missingMultiplexer()
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
internal func syncAsyncStreamMultiplexer<Output: Sendable>(continuation: any AnyContinuation, inboundStreamChannels: NIOHTTP2AsyncSequence<Output>) throws -> AsyncStreamMultiplexer<Output> {
|
||||
self.eventLoop!.preconditionInEventLoop()
|
||||
|
||||
switch self.inboundStreamMultiplexer {
|
||||
case let .some(.inline(multiplexer)):
|
||||
return AsyncStreamMultiplexer(multiplexer, continuation: continuation, inboundStreamChannels: inboundStreamChannels)
|
||||
case .some(.legacy), .none:
|
||||
throw NIOHTTP2Errors.missingMultiplexer()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -444,10 +444,120 @@ extension HTTP2CommonInboundStreamMultiplexer {
|
||||
}
|
||||
}
|
||||
|
||||
/// `ChannelContinuation` is used to generic async-sequence-like objects to deal with `Channel`s. This is so that they may be held
|
||||
/// by the `HTTP2ChannelHandler` without causing it to become generic itself.
|
||||
/// `AnyContinuation` is used to generic async-sequence-like objects to deal with the generic element types without
|
||||
/// the holding type becoming generic itself.
|
||||
///
|
||||
/// This is useful in in the case of the `HTTP2ChannelHandler` which must deal with types which hold stream initializers
|
||||
/// which have a generic return type.
|
||||
internal protocol AnyContinuation {
|
||||
func yield(any: Any)
|
||||
func finish()
|
||||
func finish(throwing error: Error)
|
||||
}
|
||||
|
||||
|
||||
/// `NIOHTTP2AsyncSequence` is an implementation of the `AsyncSequence` protocol which allows iteration over a generic
|
||||
/// element type `Output`.
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
public struct NIOHTTP2AsyncSequence<Output>: AsyncSequence {
|
||||
public struct AsyncIterator: AsyncIteratorProtocol {
|
||||
public typealias Element = Output
|
||||
|
||||
private var iterator: AsyncThrowingStream<Output, Error>.AsyncIterator
|
||||
|
||||
init(wrapping iterator: AsyncThrowingStream<Output, Error>.AsyncIterator) {
|
||||
self.iterator = iterator
|
||||
}
|
||||
|
||||
public mutating func next() async throws -> Output? {
|
||||
try await self.iterator.next()
|
||||
}
|
||||
}
|
||||
|
||||
public typealias Element = Output
|
||||
|
||||
private let asyncThrowingStream: AsyncThrowingStream<Output, Error>
|
||||
|
||||
private init(_ asyncThrowingStream: AsyncThrowingStream<Output, Error>) {
|
||||
self.asyncThrowingStream = asyncThrowingStream
|
||||
}
|
||||
|
||||
public func makeAsyncIterator() -> AsyncIterator {
|
||||
AsyncIterator(wrapping: self.asyncThrowingStream.makeAsyncIterator())
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
extension NIOHTTP2AsyncSequence {
|
||||
/// `Continuation` is a wrapper for a generic `AsyncThrowingStream` to which the products of the initializers of
|
||||
/// inbound (remotely-initiated) HTTP/2 stream channels are yielded.
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
struct Continuation: AnyContinuation {
|
||||
private var continuation: AsyncThrowingStream<Output, Error>.Continuation
|
||||
|
||||
internal init(wrapping continuation: AsyncThrowingStream<Output, Error>.Continuation) {
|
||||
self.continuation = continuation
|
||||
}
|
||||
|
||||
/// `yield` takes a channel as outputted by the stream initializer and yields the wrapped `AsyncThrowingStream`.
|
||||
///
|
||||
/// It takes channels as as `Any` type to allow wrapping by the stream initializer.
|
||||
func yield(any: Any) {
|
||||
let yieldResult = self.continuation.yield(any as! Output)
|
||||
switch yieldResult {
|
||||
case .enqueued:
|
||||
break // success, nothing to do
|
||||
case .dropped:
|
||||
preconditionFailure("Attempted to yield when AsyncThrowingStream is over capacity. This shouldn't be possible for an unbounded stream.")
|
||||
case .terminated:
|
||||
preconditionFailure("Attempted to yield to AsyncThrowingStream in terminated state.")
|
||||
default:
|
||||
preconditionFailure("Attempt to yield to AsyncThrowingStream failed for unhandled reason.")
|
||||
}
|
||||
}
|
||||
|
||||
/// `finish` marks the continuation as finished.
|
||||
func finish() {
|
||||
self.continuation.finish()
|
||||
}
|
||||
|
||||
/// `finish` marks the continuation as finished with the supplied error.
|
||||
func finish(throwing error: Error) {
|
||||
self.continuation.finish(throwing: error)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// `initialize` creates a new `Continuation` object and returns it along with its backing ``NIOHTTP2AsyncSequence``.
|
||||
/// The `Continuation` provides the ability to yield to the backing .``NIOHTTP2AsyncSequence``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - inboundStreamInitializerOutput: The type which is returned by the initializer operating on the inbound
|
||||
/// (remotely-initiated) HTTP/2 streams.
|
||||
static func initialize(inboundStreamInitializerOutput: Output.Type = Output.self) -> (NIOHTTP2AsyncSequence<Output>, Continuation) {
|
||||
let (stream, continuation) = AsyncThrowingStream.makeStream(of: Output.self)
|
||||
return (.init(stream), Continuation(wrapping: continuation))
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
extension NIOHTTP2AsyncSequence.AsyncIterator: Sendable {}
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
extension NIOHTTP2AsyncSequence: Sendable where Output: Sendable {}
|
||||
|
||||
#if swift(<5.9)
|
||||
// this should be available in the std lib from 5.9 onwards
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
extension AsyncThrowingStream {
|
||||
static func makeStream(
|
||||
of elementType: Element.Type = Element.self,
|
||||
throwing failureType: Failure.Type = Failure.self,
|
||||
bufferingPolicy limit: Continuation.BufferingPolicy = .unbounded
|
||||
) -> (stream: AsyncThrowingStream<Element, Failure>, continuation: AsyncThrowingStream<Element, Failure>.Continuation) where Failure == Error {
|
||||
var continuation: AsyncThrowingStream<Element, Failure>.Continuation!
|
||||
let stream = AsyncThrowingStream<Element, Failure>(bufferingPolicy: limit) { continuation = $0 }
|
||||
return (stream: stream, continuation: continuation!)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -416,3 +416,198 @@ extension ChannelPipeline.SynchronousOperations {
|
||||
return try handler.syncMultiplexer()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Async configurations
|
||||
|
||||
extension Channel {
|
||||
/// Configures a `ChannelPipeline` to speak HTTP/2 and sets up mapping functions so that it may be interacted with from concurrent code.
|
||||
///
|
||||
/// In general this is not entirely useful by itself, as HTTP/2 is a negotiated protocol. This helper does not handle negotiation.
|
||||
/// Instead, this simply adds the handler required to speak HTTP/2 after negotiation has completed, or when agreed by prior knowledge.
|
||||
/// Use this function to setup a HTTP/2 pipeline if you wish to use async sequence abstractions over inbound and outbound streams.
|
||||
/// Using this rather than implementing a similar function yourself allows that pipeline to evolve without breaking your code.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - mode: The mode this pipeline will operate in, server or client.
|
||||
/// - configuration: The settings that will be used when establishing the connection and new streams.
|
||||
/// - streamInitializer: A closure that will be called whenever the remote peer initiates a new stream.
|
||||
/// The output of this closure is the element type of the returned multiplexer
|
||||
/// - Returns: An `EventLoopFuture` containing the `AsyncStreamMultiplexer` inserted into this pipeline, which can
|
||||
/// be used to initiate new streams and iterate over inbound HTTP/2 stream channels.
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
public func configureAsyncHTTP2Pipeline<Output: Sendable>(
|
||||
mode: NIOHTTP2Handler.ParserMode,
|
||||
configuration: NIOHTTP2Handler.Configuration = .init(),
|
||||
streamInitializer: @escaping NIOChannelInitializerWithOutput<Output>
|
||||
) -> EventLoopFuture<NIOHTTP2Handler.AsyncStreamMultiplexer<Output>> {
|
||||
if self.eventLoop.inEventLoop {
|
||||
return self.eventLoop.makeCompletedFuture {
|
||||
return try self.pipeline.syncOperations.configureAsyncHTTP2Pipeline(
|
||||
mode: mode,
|
||||
configuration: configuration,
|
||||
streamInitializer: streamInitializer
|
||||
)
|
||||
}
|
||||
} else {
|
||||
return self.eventLoop.submit {
|
||||
return try self.pipeline.syncOperations.configureAsyncHTTP2Pipeline(
|
||||
mode: mode,
|
||||
configuration: configuration,
|
||||
streamInitializer: streamInitializer
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Configures a channel to perform an HTTP/2 secure upgrade with typed negotiation results.
|
||||
///
|
||||
/// HTTP/2 secure upgrade uses the Application Layer Protocol Negotiation TLS extension to
|
||||
/// negotiate the inner protocol as part of the TLS handshake. For this reason, until the TLS
|
||||
/// handshake is complete, the ultimate configuration of the channel pipeline cannot be known.
|
||||
///
|
||||
/// This function configures the channel with a pair of callbacks that will handle the result
|
||||
/// of the negotiation. It explicitly **does not** configure a TLS handler to actually attempt
|
||||
/// to negotiate ALPN. The supported ALPN protocols are provided in
|
||||
/// `NIOHTTP2SupportedALPNProtocols`: please ensure that the TLS handler you are using for your
|
||||
/// pipeline is appropriately configured to perform this protocol negotiation.
|
||||
///
|
||||
/// If negotiation results in an unexpected protocol, the pipeline will close the connection
|
||||
/// and no callback will fire.
|
||||
///
|
||||
/// This configuration is acceptable for use on both client and server channel pipelines.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - http1ConnectionInitializer: A callback that will be invoked if HTTP/1.1 has been explicitly
|
||||
/// negotiated, or if no protocol was negotiated. Must return a future that completes when the
|
||||
/// channel has been fully mutated.
|
||||
/// - http2ConnectionInitializer: A callback that will be invoked if HTTP/2 has been negotiated, and that
|
||||
/// should configure the channel for HTTP/2 use. Must return a future that completes when the
|
||||
/// channel has been fully mutated.
|
||||
/// - Returns: An `EventLoopFuture` of an `EventLoopFuture` containing the `NIOProtocolNegotiationResult` that completes when the channel
|
||||
/// is ready to negotiate.
|
||||
internal func configureHTTP2AsyncSecureUpgrade<HTTP1Output: Sendable, HTTP2Output: Sendable>(
|
||||
http1ConnectionInitializer: @escaping NIOChannelInitializerWithOutput<HTTP1Output>,
|
||||
http2ConnectionInitializer: @escaping NIOChannelInitializerWithOutput<HTTP2Output>
|
||||
) -> EventLoopFuture<EventLoopFuture<NIONegotiatedHTTPVersion<HTTP1Output, HTTP2Output>>> {
|
||||
let alpnHandler = NIOTypedApplicationProtocolNegotiationHandler<NIONegotiatedHTTPVersion<HTTP1Output, HTTP2Output>>() { result in
|
||||
switch result {
|
||||
case .negotiated("h2"):
|
||||
// Successful upgrade to HTTP/2. Let the user configure the pipeline.
|
||||
return http2ConnectionInitializer(self).map { http2Output in .http2(http2Output) }
|
||||
case .negotiated("http/1.1"), .fallback:
|
||||
// Explicit or implicit HTTP/1.1 choice.
|
||||
return http1ConnectionInitializer(self).map { http1Output in .http1_1(http1Output) }
|
||||
case .negotiated:
|
||||
// We negotiated something that isn't HTTP/1.1. This is a bad scene, and is a good indication
|
||||
// of a user configuration error. We're going to close the connection directly.
|
||||
return self.close().flatMap { self.eventLoop.makeFailedFuture(NIOHTTP2Errors.invalidALPNToken()) }
|
||||
}
|
||||
}
|
||||
|
||||
return self.pipeline
|
||||
.addHandler(alpnHandler)
|
||||
.map { _ in
|
||||
alpnHandler.protocolNegotiationResult
|
||||
}
|
||||
}
|
||||
|
||||
/// Configures a `ChannelPipeline` to speak either HTTP/1.1 or HTTP/2 according to what can be negotiated with the client.
|
||||
///
|
||||
/// This helper takes care of configuring the server pipeline such that it negotiates whether to
|
||||
/// use HTTP/1.1 or HTTP/2.
|
||||
///
|
||||
/// This function doesn't configure the TLS handler. Callers of this function need to add a TLS
|
||||
/// handler appropriately configured to perform protocol negotiation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - http2Configuration: The settings that will be used when establishing the HTTP/2 connections and new HTTP/2 streams.
|
||||
/// - http1ConnectionInitializer: An optional callback that will be invoked only when the negotiated protocol
|
||||
/// is HTTP/1.1 to configure the connection channel.
|
||||
/// - http2ConnectionInitializer: An optional callback that will be invoked only when the negotiated protocol
|
||||
/// is HTTP/2 to configure the connection channel.
|
||||
/// - http2StreamInitializer: A closure that will be called whenever the remote peer initiates a new stream.
|
||||
/// The output of this closure is the element type of the returned multiplexer
|
||||
/// - Returns: An `EventLoopFuture` containing a ``NIOTypedApplicationProtocolNegotiationHandler`` that completes when the channel
|
||||
/// is ready to negotiate. This can then be used to access the ``NIOProtocolNegotiationResult`` which may itself
|
||||
/// be waited on to retrieve the result of the negotiation.
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
public func configureAsyncHTTPServerPipeline<HTTP1ConnectionOutput: Sendable, HTTP2ConnectionOutput: Sendable, HTTP2StreamOutput: Sendable>(
|
||||
http2Configuration: NIOHTTP2Handler.Configuration = .init(),
|
||||
http1ConnectionInitializer: @escaping NIOChannelInitializerWithOutput<HTTP1ConnectionOutput>,
|
||||
http2ConnectionInitializer: @escaping NIOChannelInitializerWithOutput<HTTP2ConnectionOutput>,
|
||||
http2StreamInitializer: @escaping NIOChannelInitializerWithOutput<HTTP2StreamOutput>
|
||||
) -> EventLoopFuture<EventLoopFuture<NIONegotiatedHTTPVersion<
|
||||
HTTP1ConnectionOutput,
|
||||
(HTTP2ConnectionOutput, NIOHTTP2Handler.AsyncStreamMultiplexer<HTTP2StreamOutput>)
|
||||
>>> {
|
||||
let http2ConnectionInitializer: NIOChannelInitializerWithOutput<(HTTP2ConnectionOutput, NIOHTTP2Handler.AsyncStreamMultiplexer<HTTP2StreamOutput>)> = { channel in
|
||||
channel.configureAsyncHTTP2Pipeline(
|
||||
mode: .server,
|
||||
configuration: http2Configuration,
|
||||
streamInitializer: http2StreamInitializer
|
||||
).flatMap { multiplexer in
|
||||
return http2ConnectionInitializer(channel).map { connectionChannel in
|
||||
(connectionChannel, multiplexer)
|
||||
}
|
||||
}
|
||||
}
|
||||
let http1ConnectionInitializer: NIOChannelInitializerWithOutput<HTTP1ConnectionOutput> = { channel in
|
||||
channel.pipeline.configureHTTPServerPipeline().flatMap { _ in
|
||||
http1ConnectionInitializer(channel)
|
||||
}
|
||||
}
|
||||
return self.configureHTTP2AsyncSecureUpgrade(
|
||||
http1ConnectionInitializer: http1ConnectionInitializer,
|
||||
http2ConnectionInitializer: http2ConnectionInitializer
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
extension ChannelPipeline.SynchronousOperations {
|
||||
/// Configures a `ChannelPipeline` to speak HTTP/2 and sets up mapping functions so that it may be interacted with from concurrent code.
|
||||
///
|
||||
/// This operation **must** be called on the event loop.
|
||||
///
|
||||
/// In general this is not entirely useful by itself, as HTTP/2 is a negotiated protocol. This helper does not handle negotiation.
|
||||
/// Instead, this simply adds the handler required to speak HTTP/2 after negotiation has completed, or when agreed by prior knowledge.
|
||||
/// Use this function to setup a HTTP/2 pipeline if you wish to use async sequence abstractions over inbound and outbound streams,
|
||||
/// as it allows that pipeline to evolve without breaking your code.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - mode: The mode this pipeline will operate in, server or client.
|
||||
/// - configuration: The settings that will be used when establishing the connection and new streams.
|
||||
/// - streamInitializer: A closure that will be called whenever the remote peer initiates a new stream.
|
||||
/// The output of this closure is the element type of the returned multiplexer
|
||||
/// - Returns: An `EventLoopFuture` containing the `AsyncStreamMultiplexer` inserted into this pipeline, which can
|
||||
/// be used to initiate new streams and iterate over inbound HTTP/2 stream channels.
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
public func configureAsyncHTTP2Pipeline<Output: Sendable>(
|
||||
mode: NIOHTTP2Handler.ParserMode,
|
||||
configuration: NIOHTTP2Handler.Configuration = .init(),
|
||||
streamInitializer: @escaping NIOChannelInitializerWithOutput<Output>
|
||||
) throws -> NIOHTTP2Handler.AsyncStreamMultiplexer<Output> {
|
||||
let handler = NIOHTTP2Handler(
|
||||
mode: mode,
|
||||
eventLoop: self.eventLoop,
|
||||
connectionConfiguration: configuration.connection,
|
||||
streamConfiguration: configuration.stream,
|
||||
inboundStreamInitializerWithAnyOutput: { channel in
|
||||
streamInitializer(channel).map { return $0 }
|
||||
}
|
||||
)
|
||||
|
||||
try self.addHandler(handler)
|
||||
|
||||
let (inboundStreamChannels, continuation) = NIOHTTP2AsyncSequence.initialize(inboundStreamInitializerOutput: Output.self)
|
||||
|
||||
return try handler.syncAsyncStreamMultiplexer(continuation: continuation, inboundStreamChannels: inboundStreamChannels)
|
||||
}
|
||||
}
|
||||
|
||||
/// `NIONegotiatedHTTPVersion` is a generic negotiation result holder for HTTP/1.1 and HTTP/2
|
||||
public enum NIONegotiatedHTTPVersion<HTTP1Output: Sendable, HTTP2Output: Sendable> {
|
||||
/// Protocol negotiation resulted in the connection using HTTP/1.1.
|
||||
case http1_1(HTTP1Output)
|
||||
/// Protocol negotiation resulted in the connection using HTTP/2.
|
||||
case http2(HTTP2Output)
|
||||
}
|
||||
Reference in new issue
Block a user