mirror of
https://github.com/apple/swift-nio-http2
synced 2026-11-26 04:57:50 +00:00
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.
This commit is contained in:
1 parent
188fa9ba27
commit
044339de7b
8 files changed
+562
-281
No files matched your search
@@ -148,7 +148,7 @@ extension InlineStreamMultiplexer {
|
||||
self.commonStreamMultiplexer.createStreamChannel(multiplexer: .inline(self), streamStateInitializer)
|
||||
}
|
||||
|
||||
internal func createStreamChannel<Output>(_ initializer: @escaping NIOHTTP2Handler.StreamInitializerWithOutput<Output>) -> EventLoopFuture<Output> {
|
||||
internal func createStreamChannel<Output>(_ initializer: @escaping NIOChannelInitializerWithOutput<Output>) -> EventLoopFuture<Output> {
|
||||
self.commonStreamMultiplexer.createStreamChannel(multiplexer: .inline(self), initializer)
|
||||
}
|
||||
}
|
||||
@@ -239,7 +239,7 @@ extension NIOHTTP2Handler {
|
||||
}
|
||||
|
||||
/// Create a stream channel initialized with the provided closure
|
||||
public func createStreamChannel<OutboundStreamOutput>(_ initializer: @escaping NIOHTTP2Handler.StreamInitializerWithOutput<OutboundStreamOutput>) async throws -> OutboundStreamOutput {
|
||||
public func createStreamChannel<OutboundStreamOutput>(_ initializer: @escaping NIOChannelInitializerWithOutput<OutboundStreamOutput>) async throws -> OutboundStreamOutput {
|
||||
return try await self.inlineStreamMultiplexer.createStreamChannel(initializer).get()
|
||||
}
|
||||
|
||||
@@ -253,8 +253,8 @@ extension NIOHTTP2Handler {
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
@_spi(AsyncChannel)
|
||||
public func createStreamChannel<Inbound, Outbound>(
|
||||
configuration: NIOAsyncChannel<Inbound, Outbound>.Configuration,
|
||||
initializer: @escaping NIOHTTP2Handler.StreamInitializer
|
||||
configuration: NIOAsyncChannel<Inbound, Outbound>.Configuration = .init(),
|
||||
initializer: @escaping NIOChannelInitializer
|
||||
) async throws -> NIOAsyncChannel<Inbound, Outbound> {
|
||||
return try await self.createStreamChannel { channel in
|
||||
initializer(channel).flatMapThrowing { _ in
|
||||
|
||||
@@ -23,7 +23,6 @@ public let nioDefaultSettings = [
|
||||
HTTP2Setting(parameter: .maxHeaderListSize, value: HPACKDecoder.defaultMaxHeaderListSize),
|
||||
]
|
||||
|
||||
|
||||
/// ``NIOHTTP2Handler`` implements the HTTP/2 protocol for a single connection.
|
||||
///
|
||||
/// This `ChannelHandler` takes a series of bytes and turns them into a sequence of ``HTTP2Frame`` objects.
|
||||
@@ -988,19 +987,11 @@ extension NIOHTTP2Handler {
|
||||
|
||||
extension NIOHTTP2Handler {
|
||||
#if swift(>=5.7)
|
||||
/// The type of all `inboundStreamInitializer` callbacks.
|
||||
public typealias StreamInitializer = @Sendable (Channel) -> EventLoopFuture<Void>
|
||||
/// The type of all `connectionInitializer` callbacks.
|
||||
public typealias ConnectionInitializer = @Sendable (Channel) -> EventLoopFuture<Void>
|
||||
/// The type of `inboundStreamInitializer` callbacks which return non-void results.
|
||||
public typealias StreamInitializerWithOutput<Output> = @Sendable (Channel) -> EventLoopFuture<Output>
|
||||
/// The type of all `inboundStreamInitializer` callbacks which do not need to return data.
|
||||
public typealias StreamInitializer = NIOChannelInitializer
|
||||
#else
|
||||
/// The type of all `inboundStreamInitializer` callbacks.
|
||||
public typealias StreamInitializer = (Channel) -> EventLoopFuture<Void>
|
||||
/// The type of all `connectionInitializer` callbacks.
|
||||
public typealias ConnectionInitializer = (Channel) -> EventLoopFuture<Void>
|
||||
/// The type of `inboundStreamInitializer` callbacks which return non-void results.
|
||||
public typealias StreamInitializerWithOutput<Output> = (Channel) -> EventLoopFuture<Output>
|
||||
/// The type of all `inboundStreamInitializer` callbacks which need to return data.
|
||||
public typealias StreamInitializer = NIOChannelInitializer
|
||||
#endif
|
||||
|
||||
/// Creates a new ``NIOHTTP2Handler`` with a local multiplexer. (i.e. using
|
||||
@@ -1035,6 +1026,9 @@ extension NIOHTTP2Handler {
|
||||
}
|
||||
|
||||
/// Connection-level configuration.
|
||||
///
|
||||
/// The settings that will be used when establishing the connection. These will be sent to the peer as part of the
|
||||
/// handshake.
|
||||
public struct ConnectionConfiguration: Hashable, Sendable {
|
||||
public var initialSettings: HTTP2Settings = nioDefaultSettings
|
||||
public var headerBlockValidation: ValidationState = .enabled
|
||||
@@ -1045,6 +1039,8 @@ extension NIOHTTP2Handler {
|
||||
}
|
||||
|
||||
/// Stream-level configuration.
|
||||
///
|
||||
/// The settings that will be used when establishing new streams. These mainly pertain to flow control.
|
||||
public struct StreamConfiguration: Hashable, Sendable {
|
||||
public var targetWindowSize: Int = 65535
|
||||
public var outboundBufferSizeHighWatermark: Int = 8196
|
||||
@@ -1052,6 +1048,25 @@ extension NIOHTTP2Handler {
|
||||
public init() {}
|
||||
}
|
||||
|
||||
/// Overall connection and stream-level configuration.
|
||||
public struct Configuration: Hashable, Sendable {
|
||||
/// The settings that will be used when establishing the connection. These will be sent to the peer as part of the
|
||||
/// handshake.
|
||||
public var connection: ConnectionConfiguration
|
||||
/// The settings that will be used when establishing new streams. These mainly pertain to flow control.
|
||||
public var stream: StreamConfiguration
|
||||
|
||||
public init() {
|
||||
self.connection = .init()
|
||||
self.stream = .init()
|
||||
}
|
||||
|
||||
public init(connection: ConnectionConfiguration, stream: StreamConfiguration) {
|
||||
self.connection = connection
|
||||
self.stream = stream
|
||||
}
|
||||
}
|
||||
|
||||
/// An `EventLoopFuture` which returns a ``StreamMultiplexer`` which can be used to create new outbound HTTP/2 streams.
|
||||
///
|
||||
/// > Note: This is only safe to get if the ``NIOHTTP2Handler`` uses a local multiplexer,
|
||||
|
||||
@@ -286,7 +286,7 @@ extension HTTP2CommonInboundStreamMultiplexer {
|
||||
internal func _createStreamChannel<Output>(
|
||||
_ multiplexer: HTTP2StreamChannel.OutboundStreamMultiplexer,
|
||||
_ promise: EventLoopPromise<Output>?,
|
||||
_ streamStateInitializer: @escaping NIOHTTP2Handler.StreamInitializerWithOutput<Output>
|
||||
_ streamStateInitializer: @escaping NIOChannelInitializerWithOutput<Output>
|
||||
) {
|
||||
self.channel.eventLoop.assertInEventLoop()
|
||||
|
||||
@@ -307,7 +307,7 @@ extension HTTP2CommonInboundStreamMultiplexer {
|
||||
internal func createStreamChannel<Output>(
|
||||
multiplexer: HTTP2StreamChannel.OutboundStreamMultiplexer,
|
||||
promise: EventLoopPromise<Output>?,
|
||||
_ streamStateInitializer: @escaping NIOHTTP2Handler.StreamInitializerWithOutput<Output>
|
||||
_ streamStateInitializer: @escaping NIOChannelInitializerWithOutput<Output>
|
||||
) {
|
||||
if self.channel.eventLoop.inEventLoop {
|
||||
self._createStreamChannel(multiplexer, promise, streamStateInitializer)
|
||||
@@ -320,7 +320,7 @@ extension HTTP2CommonInboundStreamMultiplexer {
|
||||
|
||||
internal func createStreamChannel<Output>(
|
||||
multiplexer: HTTP2StreamChannel.OutboundStreamMultiplexer,
|
||||
_ streamStateInitializer: @escaping NIOHTTP2Handler.StreamInitializerWithOutput<Output>
|
||||
_ streamStateInitializer: @escaping NIOChannelInitializerWithOutput<Output>
|
||||
) -> EventLoopFuture<Output> {
|
||||
let promise = self.channel.eventLoop.makePromise(of: Output.self)
|
||||
self.createStreamChannel(multiplexer: multiplexer, promise: promise, streamStateInitializer)
|
||||
@@ -426,11 +426,11 @@ internal protocol ChannelContinuation {
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
struct StreamChannelContinuation<Output>: ChannelContinuation {
|
||||
private var continuation: AsyncThrowingStream<Output, Error>.Continuation
|
||||
private let inboundStreamInititializer: NIOHTTP2Handler.StreamInitializerWithOutput<Output>
|
||||
private let inboundStreamInititializer: NIOChannelInitializerWithOutput<Output>
|
||||
|
||||
private init(
|
||||
continuation: AsyncThrowingStream<Output, Error>.Continuation,
|
||||
inboundStreamInititializer: @escaping NIOHTTP2Handler.StreamInitializerWithOutput<Output>
|
||||
inboundStreamInititializer: @escaping NIOChannelInitializerWithOutput<Output>
|
||||
) {
|
||||
self.continuation = continuation
|
||||
self.inboundStreamInititializer = inboundStreamInititializer
|
||||
@@ -446,7 +446,7 @@ struct StreamChannelContinuation<Output>: ChannelContinuation {
|
||||
/// have a `Output` corresponding to that `NIOAsyncChannel` type. Another example is in cases where there is
|
||||
/// per-stream protocol negotiation where `Output` would be some form of `NIOProtocolNegotiationResult`.
|
||||
static func initialize(
|
||||
with inboundStreamInititializer: @escaping NIOHTTP2Handler.StreamInitializerWithOutput<Output>
|
||||
with inboundStreamInititializer: @escaping NIOChannelInitializerWithOutput<Output>
|
||||
) -> (StreamChannelContinuation<Output>, NIOHTTP2InboundStreamChannels<Output>) {
|
||||
let (stream, continuation) = AsyncThrowingStream.makeStream(of: Output.self)
|
||||
return (StreamChannelContinuation(continuation: continuation, inboundStreamInititializer: inboundStreamInititializer), NIOHTTP2InboundStreamChannels(stream))
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@_spi(AsyncChannel) import NIOCore
|
||||
import NIOTLS
|
||||
@_spi(AsyncChannel) import NIOTLS
|
||||
|
||||
/// The supported ALPN protocol tokens for NIO's HTTP/2 abstraction layer.
|
||||
///
|
||||
@@ -32,6 +32,18 @@ import NIOTLS
|
||||
/// Configuring for servers is very similar.
|
||||
public let NIOHTTP2SupportedALPNProtocols = ["h2", "http/1.1"]
|
||||
|
||||
#if swift(>=5.7)
|
||||
/// The type of NIO Channel initializer callbacks which do not need to return data.
|
||||
public typealias NIOChannelInitializer = @Sendable (Channel) -> EventLoopFuture<Void>
|
||||
/// The type of NIO Channel initializer callbacks which need to return data.
|
||||
public typealias NIOChannelInitializerWithOutput<Output> = @Sendable (Channel) -> EventLoopFuture<Output>
|
||||
#else
|
||||
/// The type of NIO Channel initializer callbacks which do not need to return data.
|
||||
public typealias NIOChannelInitializer = (Channel) -> EventLoopFuture<Void>
|
||||
/// The type of NIO Channel initializer callbacks which need to return data.
|
||||
public typealias NIOChannelInitializerWithOutput<Output> = (Channel) -> EventLoopFuture<Output>
|
||||
#endif
|
||||
|
||||
extension ChannelPipeline {
|
||||
/// Configures a channel pipeline to perform a HTTP/2 secure upgrade.
|
||||
///
|
||||
@@ -51,7 +63,7 @@ extension ChannelPipeline {
|
||||
/// This configuration is acceptable for use on both client and server channel pipelines.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - h2PipelineConfigurator: A callback that will be invoked if HTTP/2 has been negogiated, and that
|
||||
/// - h2PipelineConfigurator: A callback that will be invoked if HTTP/2 has been negotiated, and that
|
||||
/// should configure the pipeline for HTTP/2 use. Must return a future that completes when the
|
||||
/// pipeline has been fully mutated.
|
||||
/// - http1PipelineConfigurator: A callback that will be invoked if HTTP/1.1 has been explicitly
|
||||
@@ -182,7 +194,7 @@ extension Channel {
|
||||
streamConfiguration: NIOHTTP2Handler.StreamConfiguration,
|
||||
streamDelegate: NIOHTTP2StreamDelegate? = nil,
|
||||
position: ChannelPipeline.Position = .last,
|
||||
inboundStreamInitializer: @escaping NIOHTTP2Handler.StreamInitializer) -> EventLoopFuture<NIOHTTP2Handler.StreamMultiplexer> {
|
||||
inboundStreamInitializer: @escaping NIOChannelInitializer) -> EventLoopFuture<NIOHTTP2Handler.StreamMultiplexer> {
|
||||
if self.eventLoop.inEventLoop {
|
||||
return self.eventLoop.makeCompletedFuture {
|
||||
return try self.pipeline.syncOperations.configureHTTP2Pipeline(
|
||||
@@ -217,10 +229,7 @@ extension Channel {
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - mode: The mode this pipeline will operate in, server or client.
|
||||
/// - connectionConfiguration: The settings that will be used when establishing the connection. These will be sent to the peer as part of the
|
||||
/// handshake.
|
||||
/// - streamConfiguration: The settings that will be used when establishing new streams. These mainly pertain to flow control.
|
||||
/// - streamDelegate: The delegate to be notified in the event of stream creation and close.
|
||||
/// - configuration: The settings that will be used when establishing the connection and new streams.
|
||||
/// - position: The position in the pipeline into which to insert this handler.
|
||||
/// - inboundStreamInitializer: A closure that will be called whenever the remote peer initiates a new stream.
|
||||
/// - Returns: An `EventLoopFuture` containing the `AsyncStreamMultiplexer` inserted into this pipeline, which can
|
||||
@@ -229,19 +238,15 @@ extension Channel {
|
||||
@_spi(AsyncChannel)
|
||||
public func configureAsyncHTTP2Pipeline<Output>(
|
||||
mode: NIOHTTP2Handler.ParserMode,
|
||||
connectionConfiguration: NIOHTTP2Handler.ConnectionConfiguration,
|
||||
streamConfiguration: NIOHTTP2Handler.StreamConfiguration,
|
||||
streamDelegate: NIOHTTP2StreamDelegate? = nil,
|
||||
configuration: NIOHTTP2Handler.Configuration = .init(),
|
||||
position: ChannelPipeline.Position = .last,
|
||||
inboundStreamInitializer: @escaping NIOHTTP2Handler.StreamInitializerWithOutput<Output>
|
||||
inboundStreamInitializer: @escaping NIOChannelInitializerWithOutput<Output>
|
||||
) -> EventLoopFuture<NIOHTTP2Handler.AsyncStreamMultiplexer<Output>> {
|
||||
if self.eventLoop.inEventLoop {
|
||||
return self.eventLoop.makeCompletedFuture {
|
||||
return try self.pipeline.syncOperations.configureAsyncHTTP2Pipeline(
|
||||
mode: mode,
|
||||
connectionConfiguration: connectionConfiguration,
|
||||
streamConfiguration: streamConfiguration,
|
||||
streamDelegate: streamDelegate,
|
||||
configuration: configuration,
|
||||
position: position,
|
||||
inboundStreamInitializer: inboundStreamInitializer
|
||||
)
|
||||
@@ -250,9 +255,7 @@ extension Channel {
|
||||
return self.eventLoop.submit {
|
||||
return try self.pipeline.syncOperations.configureAsyncHTTP2Pipeline(
|
||||
mode: mode,
|
||||
connectionConfiguration: connectionConfiguration,
|
||||
streamConfiguration: streamConfiguration,
|
||||
streamDelegate: streamDelegate,
|
||||
configuration: configuration,
|
||||
position: position,
|
||||
inboundStreamInitializer: inboundStreamInitializer
|
||||
)
|
||||
@@ -271,49 +274,32 @@ extension Channel {
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - mode: The mode this pipeline will operate in, server or client.
|
||||
/// - inboundStreamAsyncChannelConfiguration: Settings relating to `NIOAsyncChannel`s wrapping internal stream channels.
|
||||
/// - connectionConfiguration: The settings that will be used when establishing the connection. These will be sent to the peer as part of the
|
||||
/// handshake.
|
||||
/// - streamConfiguration: The settings that will be used when establishing new streams. These mainly pertain to flow control.
|
||||
/// - streamDelegate: The delegate to be notified in the event of stream creation and close.
|
||||
/// - position: The position in the pipeline into which to insert the `NIOHTTP2Handler`.
|
||||
/// - inboundStreamBackpressureStrategy: The backpressure strategy of the ``NIOAsyncChannel``s wrapping inbound HTTP/2 streams.
|
||||
/// - isInboundStreamOutboundHalfClosureEnabled: If outbound half closure should be enabled for the ``NIOAsyncChannel``s wrapping inbound HTTP/2 streams.
|
||||
/// - streamInboundType: The ``NIOAsyncChannel/inboundStream`` message type for inbound stream channels.
|
||||
/// This type must match the `InboundOut` type of the final handler added to the stream channel by the `inboundStreamInitializer`
|
||||
/// or ``HTTP2Frame/FramePayload`` if there are none.
|
||||
/// - streamOutboundType: The ``NIOAsyncChannel/outboundWriter`` message type for inbound stream channels.
|
||||
/// This type must match the `OutboundIn` type of the final handler added to the stream channel by the `inboundStreamInitializer`
|
||||
/// or ``HTTP2Frame/FramePayload`` if there are none.
|
||||
/// - inboundStreamInitializer: A closure that will be called whenever the remote peer initiates a new stream.
|
||||
/// - Returns: An `EventLoopFuture` containing the `AsyncStreamMultiplexer` inserted into this pipeline which wraps
|
||||
/// inbound streams as `NIOAsyncChannels` after initialization. The multiplexer 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, *)
|
||||
@_spi(AsyncChannel)
|
||||
public func configureAsyncHTTP2Pipeline<StreamInbound, StreamOutbound>(
|
||||
internal func configureAsyncHTTP2Pipeline<StreamInbound, StreamOutbound>(
|
||||
mode: NIOHTTP2Handler.ParserMode,
|
||||
connectionConfiguration: NIOHTTP2Handler.ConnectionConfiguration,
|
||||
streamConfiguration: NIOHTTP2Handler.StreamConfiguration,
|
||||
streamDelegate: NIOHTTP2StreamDelegate? = nil,
|
||||
inboundStreamAsyncChannelConfiguration: NIOAsyncChannel<StreamInbound, StreamOutbound>.Configuration,
|
||||
connectionConfiguration: NIOHTTP2Handler.ConnectionConfiguration = .init(),
|
||||
streamConfiguration: NIOHTTP2Handler.StreamConfiguration = .init(),
|
||||
position: ChannelPipeline.Position = .last,
|
||||
inboundStreamBackpressureStrategy: NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark? = nil,
|
||||
isInboundStreamOutboundHalfClosureEnabled: Bool = false,
|
||||
streamInboundType: StreamInbound.Type = StreamInbound.self,
|
||||
streamOutboundType: StreamOutbound.Type = StreamOutbound.self,
|
||||
inboundStreamInitializer: @escaping NIOHTTP2Handler.StreamInitializer
|
||||
inboundStreamInitializer: @escaping NIOChannelInitializer
|
||||
) throws -> EventLoopFuture<NIOHTTP2Handler.AsyncStreamMultiplexer<NIOAsyncChannel<StreamInbound, StreamOutbound>>> {
|
||||
if self.eventLoop.inEventLoop {
|
||||
return self.eventLoop.makeCompletedFuture {
|
||||
return try self.pipeline.syncOperations.configureAsyncHTTP2Pipeline(
|
||||
mode: mode,
|
||||
inboundStreamAsyncChannelConfiguration: inboundStreamAsyncChannelConfiguration,
|
||||
connectionConfiguration: connectionConfiguration,
|
||||
streamConfiguration: streamConfiguration,
|
||||
streamDelegate: streamDelegate,
|
||||
position: position,
|
||||
inboundStreamBackpressureStrategy: inboundStreamBackpressureStrategy,
|
||||
isInboundStreamOutboundHalfClosureEnabled: isInboundStreamOutboundHalfClosureEnabled,
|
||||
streamInboundType: streamInboundType,
|
||||
streamOutboundType: streamOutboundType,
|
||||
inboundStreamInitializer: inboundStreamInitializer
|
||||
)
|
||||
}
|
||||
@@ -321,21 +307,17 @@ extension Channel {
|
||||
return self.eventLoop.submit {
|
||||
return try self.pipeline.syncOperations.configureAsyncHTTP2Pipeline(
|
||||
mode: mode,
|
||||
inboundStreamAsyncChannelConfiguration: inboundStreamAsyncChannelConfiguration,
|
||||
connectionConfiguration: connectionConfiguration,
|
||||
streamConfiguration: streamConfiguration,
|
||||
streamDelegate: streamDelegate,
|
||||
position: position,
|
||||
inboundStreamBackpressureStrategy: inboundStreamBackpressureStrategy,
|
||||
isInboundStreamOutboundHalfClosureEnabled: isInboundStreamOutboundHalfClosureEnabled,
|
||||
streamInboundType: streamInboundType,
|
||||
streamOutboundType: streamOutboundType,
|
||||
inboundStreamInitializer: inboundStreamInitializer
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Configures a channel to perform a HTTP/2 secure upgrade.
|
||||
/// Configures a channel to perform an HTTP/2 secure upgrade.
|
||||
///
|
||||
/// 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
|
||||
@@ -353,7 +335,7 @@ extension Channel {
|
||||
/// This configuration is acceptable for use on both client and server channel pipelines.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - h2ChannelConfigurator: A callback that will be invoked if HTTP/2 has been negogiated, and that
|
||||
/// - h2ChannelConfigurator: 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.
|
||||
/// - http1ChannelConfigurator: A callback that will be invoked if HTTP/1.1 has been explicitly
|
||||
@@ -380,7 +362,59 @@ extension Channel {
|
||||
return self.pipeline.addHandler(alpnHandler)
|
||||
}
|
||||
|
||||
/// Configures a `ChannelPipeline` to speak either HTTP or HTTP/2 according to what can be negotiated with the client.
|
||||
|
||||
/// 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` 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.
|
||||
internal func configureHTTP2AsyncSecureUpgrade<HTTP1Output, HTTP2Output>(
|
||||
http1ConnectionInitializer: @escaping NIOChannelInitializerWithOutput<HTTP1Output>,
|
||||
http2ConnectionInitializer: @escaping NIOChannelInitializerWithOutput<HTTP2Output>
|
||||
) -> EventLoopFuture<NIOTypedApplicationProtocolNegotiationHandler<NIONegotiatedHTTPVersion<HTTP1Output, HTTP2Output>>> {
|
||||
let alpnHandler = NIOTypedApplicationProtocolNegotiationHandler<NIONegotiatedHTTPVersion<HTTP1Output, HTTP2Output>>(eventLoop: self.eventLoop) { result in
|
||||
switch result {
|
||||
case .negotiated("h2"):
|
||||
// Successful upgrade to HTTP/2. Let the user configure the pipeline.
|
||||
return http2ConnectionInitializer(self).map { http2Output in .finished(.http2(http2Output)) }
|
||||
case .negotiated("http/1.1"), .fallback:
|
||||
// Explicit or implicit HTTP/1.1 choice.
|
||||
return http1ConnectionInitializer(self).map { http1Output in .finished(.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
|
||||
}
|
||||
}
|
||||
|
||||
/// 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. Once the protocol to use for the channel has been negotiated, the
|
||||
@@ -403,7 +437,7 @@ extension Channel {
|
||||
return self.configureCommonHTTPServerPipeline(h2ConnectionChannelConfigurator: h2ConnectionChannelConfigurator, targetWindowSize: 65535, configurator)
|
||||
}
|
||||
|
||||
/// Configures a `ChannelPipeline` to speak either HTTP or HTTP/2 according to what can be negotiated with the client.
|
||||
/// 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. Once the protocol to use for the channel has been negotiated, the
|
||||
@@ -434,6 +468,47 @@ extension Channel {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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. Once the protocol to use for the channel has been negotiated, the
|
||||
/// provided callback will configure the application-specific handlers in a protocol-agnostic way.
|
||||
///
|
||||
/// 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:
|
||||
/// - connectionConfiguration: The settings that will be used when establishing the HTTP/2 connection. These will be sent to the peer as part of the
|
||||
/// handshake.
|
||||
/// - streamConfiguration: The settings that will be used when establishing new HTTP/2 streams. These mainly pertain to flow control.
|
||||
/// - streamDelegate: The delegate to be notified in the event of stream creation and close.
|
||||
/// - h2ConnectionChannelConfigurator: An optional callback that will be invoked only
|
||||
/// when the negotiated protocol is H2 to configure the connection channel.
|
||||
/// - configurator: A callback that will be invoked after a protocol has been negotiated.
|
||||
/// The callback only needs to add application-specific handlers and must return a future
|
||||
/// that completes when the channel has been fully mutated.
|
||||
/// - Returns: `EventLoopFuture<Void>` that completes when the channel is ready.
|
||||
public func configureCommonHTTPServerPipeline(
|
||||
connectionConfiguration: NIOHTTP2Handler.ConnectionConfiguration,
|
||||
streamConfiguration: NIOHTTP2Handler.StreamConfiguration,
|
||||
streamDelegate: NIOHTTP2StreamDelegate? = nil,
|
||||
h2ConnectionChannelConfigurator: ((Channel) -> EventLoopFuture<Void>)? = nil,
|
||||
configurator: @escaping NIOChannelInitializer
|
||||
) -> EventLoopFuture<Void> {
|
||||
return self._commonHTTPServerPipeline(configurator: configurator, h2ConnectionChannelConfigurator: h2ConnectionChannelConfigurator) { channel in
|
||||
channel.configureHTTP2Pipeline(
|
||||
mode: .server,
|
||||
connectionConfiguration: connectionConfiguration,
|
||||
streamConfiguration: streamConfiguration,
|
||||
streamDelegate: streamDelegate
|
||||
) { streamChannel -> EventLoopFuture<Void> in
|
||||
streamChannel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ServerCodec()).flatMap { () -> EventLoopFuture<Void> in
|
||||
configurator(streamChannel)
|
||||
}
|
||||
}.map { _ in () }
|
||||
}
|
||||
}
|
||||
|
||||
private func _commonHTTPServerPipeline(
|
||||
configurator: @escaping (Channel) -> EventLoopFuture<Void>,
|
||||
h2ConnectionChannelConfigurator: ((Channel) -> EventLoopFuture<Void>)?,
|
||||
@@ -457,43 +532,55 @@ extension Channel {
|
||||
http1ChannelConfigurator: http1ChannelConfigurator)
|
||||
}
|
||||
|
||||
/// Configures a `ChannelPipeline` to speak either HTTP or HTTP/2 according to what can be negotiated with the client.
|
||||
/// 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. Once the protocol to use for the channel has been negotiated, the
|
||||
/// provided callback will configure the application-specific handlers in a protocol-agnostic way.
|
||||
/// 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:
|
||||
/// - connectionConfiguration: The settings that will be used when establishing the connection. These will be sent to the peer as part of the
|
||||
/// handshake.
|
||||
/// - streamConfiguration: The settings that will be used when establishing new streams. These mainly pertain to flow control.
|
||||
/// - streamDelegate: The delegate to be notified in the event of stream creation and close.
|
||||
/// - h2ConnectionChannelConfigurator: An optional callback that will be invoked only
|
||||
/// when the negotiated protocol is H2 to configure the connection channel.
|
||||
/// - inboundStreamInitializer: A closure that will be called whenever the remote peer initiates a new stream.
|
||||
/// - Returns: `EventLoopFuture<Void>` that completes when the channel is ready.
|
||||
public func configureCommonHTTPServerPipeline(
|
||||
connectionConfiguration: NIOHTTP2Handler.ConnectionConfiguration,
|
||||
streamConfiguration: NIOHTTP2Handler.StreamConfiguration,
|
||||
streamDelegate: NIOHTTP2StreamDelegate? = nil,
|
||||
h2ConnectionChannelConfigurator: ((Channel) -> EventLoopFuture<Void>)? = nil,
|
||||
configurator: @escaping NIOHTTP2Handler.StreamInitializer
|
||||
) -> EventLoopFuture<Void> {
|
||||
return self._commonHTTPServerPipeline(configurator: configurator, h2ConnectionChannelConfigurator: h2ConnectionChannelConfigurator) { channel in
|
||||
channel.configureHTTP2Pipeline(
|
||||
/// - 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.
|
||||
/// - http2InboundStreamInitializer: A closure that will be called whenever the remote peer initiates a new stream.
|
||||
/// - 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, *)
|
||||
@_spi(AsyncChannel)
|
||||
public func configureAsyncHTTPServerPipeline<HTTP1ConnectionOutput, HTTP2ConnectionOutput, HTTP2StreamOutput>(
|
||||
http2Configuration: NIOHTTP2Handler.Configuration = .init(),
|
||||
http1ConnectionInitializer: @escaping NIOChannelInitializerWithOutput<HTTP1ConnectionOutput>,
|
||||
http2ConnectionInitializer: @escaping NIOChannelInitializerWithOutput<HTTP2ConnectionOutput>,
|
||||
http2InboundStreamInitializer: @escaping NIOChannelInitializerWithOutput<HTTP2StreamOutput>
|
||||
) throws -> EventLoopFuture<NIOTypedApplicationProtocolNegotiationHandler<NIONegotiatedHTTPVersion<
|
||||
HTTP1ConnectionOutput,
|
||||
(HTTP2ConnectionOutput, NIOHTTP2Handler.AsyncStreamMultiplexer<HTTP2StreamOutput>)
|
||||
>>> {
|
||||
let http2ConnectionInitializer: NIOChannelInitializerWithOutput<(HTTP2ConnectionOutput, NIOHTTP2Handler.AsyncStreamMultiplexer<HTTP2StreamOutput>)> = { channel in
|
||||
channel.configureAsyncHTTP2Pipeline(
|
||||
mode: .server,
|
||||
connectionConfiguration: connectionConfiguration,
|
||||
streamConfiguration: streamConfiguration,
|
||||
streamDelegate: streamDelegate
|
||||
) { streamChannel -> EventLoopFuture<Void> in
|
||||
streamChannel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ServerCodec()).flatMap { () -> EventLoopFuture<Void> in
|
||||
configurator(streamChannel)
|
||||
configuration: http2Configuration,
|
||||
inboundStreamInitializer: http2InboundStreamInitializer
|
||||
).flatMap { multiplexer in
|
||||
return http2ConnectionInitializer(channel).map { connectionChannel in
|
||||
(connectionChannel, multiplexer)
|
||||
}
|
||||
}.map { _ in () }
|
||||
}
|
||||
}
|
||||
let http1ConnectionInitializer: NIOChannelInitializerWithOutput<HTTP1ConnectionOutput> = { channel in
|
||||
channel.pipeline.configureHTTPServerPipeline().flatMap { _ in
|
||||
http1ConnectionInitializer(channel)
|
||||
}
|
||||
}
|
||||
return self.configureHTTP2AsyncSecureUpgrade(
|
||||
http1ConnectionInitializer: http1ConnectionInitializer,
|
||||
http2ConnectionInitializer: http2ConnectionInitializer
|
||||
)
|
||||
}
|
||||
|
||||
/// Configures a `ChannelPipeline` to speak HTTP/2 and wraps both the connection channel and any
|
||||
@@ -508,27 +595,8 @@ extension Channel {
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - mode: The mode this pipeline will operate in, server or client.
|
||||
/// - connectionConfiguration: The settings that will be used when establishing the connection. These will be sent to the peer as part of the
|
||||
/// handshake.
|
||||
/// - streamConfiguration: The settings that will be used when establishing new streams. These mainly pertain to flow control.
|
||||
/// - streamDelegate: The delegate to be notified in the event of stream creation and close.
|
||||
/// - position: The position in the pipeline into which to insert the `NIOHTTP2Handler`.
|
||||
/// - connectionBackpressureStrategy: The backpressure strategy of the ``NIOAsyncChannel`` wrapping the HTTP/2 connection channel.
|
||||
/// - isConnectionOutboundHalfClosureEnabled: If outbound half closure should be enabled for the ``NIOAsyncChannel`` wrapping the HTTP/2 connection channel.
|
||||
/// - connectionInboundType: The ``NIOAsyncChannel/inboundStream`` message type for the HTTP/2 connection channel.
|
||||
/// This type must match the `InboundOut` type of the final handler in the connection channel.
|
||||
/// - connectionOutboundType: The ``NIOAsyncChannel/outboundWriter`` message type for the HTTP/2 connection channel.
|
||||
/// This type must match the `OutboundIn` type of the final handler in the connection channel.
|
||||
/// - inboundStreamBackpressureStrategy: The backpressure strategy of the ``NIOAsyncChannel``s wrapping inbound HTTP/2 streams.
|
||||
/// - isInboundStreamOutboundHalfClosureEnabled: If outbound half closure should be enabled for the ``NIOAsyncChannel``s wrapping inbound HTTP/2 streams.
|
||||
/// - streamInboundType: The ``NIOAsyncChannel/inboundStream`` message type for inbound stream channels.
|
||||
/// This type must match the `InboundOut` type of the final handler added to the stream channel by the `inboundStreamInitializer`
|
||||
/// or ``HTTP2Frame/FramePayload`` if there are none.
|
||||
/// - streamOutboundType: The ``NIOAsyncChannel/outboundWriter`` message type for inbound stream channels.
|
||||
/// This type must match the `OutboundIn` type of the final handler added to the stream channel by the `inboundStreamInitializer`
|
||||
/// or ``HTTP2Frame/FramePayload`` if there are none.
|
||||
/// - connectionInitializer: A closure that will be called once the `NIOHTTP2Handler` has been added to the pipeline.
|
||||
/// - inboundStreamInitializer: A closure that will be called whenever the remote peer initiates a new stream.
|
||||
/// - configuration: The settings and initialization configuration for both connections and streams, and their wrapping
|
||||
/// ``NIOAsyncChannel``s.
|
||||
/// - Returns: An `EventLoopFuture` containing the `AsyncStreamMultiplexer` inserted into this pipeline which wraps
|
||||
/// inbound streams as `NIOAsyncChannels` after initialization. The multiplexer can be used to initiate new streams
|
||||
/// and iterate over inbound HTTP/2 stream channels.
|
||||
@@ -536,46 +604,29 @@ extension Channel {
|
||||
@_spi(AsyncChannel)
|
||||
public func configureAsyncHTTP2Pipeline<ConnectionInbound, ConnectionOutbound, StreamInbound, StreamOutbound>(
|
||||
mode: NIOHTTP2Handler.ParserMode,
|
||||
connectionConfiguration: NIOHTTP2Handler.ConnectionConfiguration,
|
||||
streamConfiguration: NIOHTTP2Handler.StreamConfiguration,
|
||||
streamDelegate: NIOHTTP2StreamDelegate? = nil,
|
||||
connectionBackpressureStrategy: NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark? = nil,
|
||||
isConnectionOutboundHalfClosureEnabled: Bool = false,
|
||||
connectionInboundType: ConnectionInbound.Type = ConnectionInbound.self,
|
||||
connectionOutboundType: ConnectionOutbound.Type = ConnectionOutbound.self,
|
||||
inboundStreamBackpressureStrategy: NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark? = nil,
|
||||
isInboundStreamOutboundHalfClosureEnabled: Bool = false,
|
||||
streamInboundType: StreamInbound.Type = StreamInbound.self,
|
||||
streamOutboundType: StreamOutbound.Type = StreamOutbound.self,
|
||||
connectionInitializer: @escaping NIOHTTP2Handler.ConnectionInitializer,
|
||||
inboundStreamInitializer: @escaping NIOHTTP2Handler.StreamInitializer
|
||||
) throws -> EventLoopFuture<(
|
||||
configuration: NIOHTTP2AsyncConfiguration<ConnectionInbound, ConnectionOutbound, StreamInbound, StreamOutbound>
|
||||
) -> EventLoopFuture<(
|
||||
NIOAsyncChannel<ConnectionInbound, ConnectionOutbound>,
|
||||
NIOHTTP2Handler.AsyncStreamMultiplexer<NIOAsyncChannel<StreamInbound, StreamOutbound>>
|
||||
)> {
|
||||
return try self.configureAsyncHTTP2Pipeline(
|
||||
mode: mode,
|
||||
connectionConfiguration: connectionConfiguration,
|
||||
streamConfiguration: streamConfiguration,
|
||||
streamDelegate: streamDelegate,
|
||||
inboundStreamBackpressureStrategy: inboundStreamBackpressureStrategy,
|
||||
isInboundStreamOutboundHalfClosureEnabled: isInboundStreamOutboundHalfClosureEnabled,
|
||||
streamInboundType: streamInboundType,
|
||||
streamOutboundType: streamOutboundType,
|
||||
inboundStreamInitializer: inboundStreamInitializer
|
||||
).flatMap { multiplexer in
|
||||
return connectionInitializer(self).flatMapThrowing { _ in
|
||||
let connectionAsyncChannel = try NIOAsyncChannel(
|
||||
synchronouslyWrapping: self,
|
||||
configuration: .init(
|
||||
backpressureStrategy: connectionBackpressureStrategy ?? .init(lowWatermark: 2, highWatermark: 10),
|
||||
isOutboundHalfClosureEnabled: isConnectionOutboundHalfClosureEnabled,
|
||||
inboundType: ConnectionInbound.self,
|
||||
outboundType: ConnectionOutbound.self
|
||||
do {
|
||||
return try self.configureAsyncHTTP2Pipeline(
|
||||
mode: mode,
|
||||
inboundStreamAsyncChannelConfiguration: configuration.inboundStreamAsyncChannel,
|
||||
connectionConfiguration: configuration.connection,
|
||||
streamConfiguration: configuration.stream,
|
||||
inboundStreamInitializer: configuration.inboundStreamInitializer
|
||||
).flatMap { multiplexer in
|
||||
return configuration.connectionInitializer(self).flatMapThrowing { _ in
|
||||
let connectionAsyncChannel = try NIOAsyncChannel<ConnectionInbound, ConnectionOutbound>(
|
||||
synchronouslyWrapping: self,
|
||||
configuration: configuration.connectionAsyncChannel
|
||||
)
|
||||
)
|
||||
return (connectionAsyncChannel, multiplexer)
|
||||
return (connectionAsyncChannel, multiplexer)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
return self.eventLoop.makeFailedFuture(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -603,7 +654,7 @@ extension ChannelPipeline.SynchronousOperations {
|
||||
streamConfiguration: NIOHTTP2Handler.StreamConfiguration,
|
||||
streamDelegate: NIOHTTP2StreamDelegate? = nil,
|
||||
position: ChannelPipeline.Position = .last,
|
||||
inboundStreamInitializer: @escaping NIOHTTP2Handler.StreamInitializer) throws -> NIOHTTP2Handler.StreamMultiplexer {
|
||||
inboundStreamInitializer: @escaping NIOChannelInitializer) throws -> NIOHTTP2Handler.StreamMultiplexer {
|
||||
let handler = NIOHTTP2Handler(
|
||||
mode: mode,
|
||||
eventLoop: self.eventLoop,
|
||||
@@ -630,10 +681,7 @@ extension ChannelPipeline.SynchronousOperations {
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - mode: The mode this pipeline will operate in, server or client.
|
||||
/// - connectionConfiguration: The settings that will be used when establishing the connection. These will be sent to the peer as part of the
|
||||
/// handshake.
|
||||
/// - streamConfiguration: The settings that will be used when establishing new streams. These mainly pertain to flow control.
|
||||
/// - streamDelegate: The delegate to be notified in the event of stream creation and close.
|
||||
/// - configuration: The settings that will be used when establishing the connection and new streams.
|
||||
/// - position: The position in the pipeline into which to insert this handler.
|
||||
/// - inboundStreamInitializer: A closure that will be called whenever the remote peer initiates a new stream.
|
||||
/// - Returns: An `EventLoopFuture` containing the `AsyncStreamMultiplexer` inserted into this pipeline, which can
|
||||
@@ -642,18 +690,15 @@ extension ChannelPipeline.SynchronousOperations {
|
||||
@_spi(AsyncChannel)
|
||||
public func configureAsyncHTTP2Pipeline<Output>(
|
||||
mode: NIOHTTP2Handler.ParserMode,
|
||||
connectionConfiguration: NIOHTTP2Handler.ConnectionConfiguration,
|
||||
streamConfiguration: NIOHTTP2Handler.StreamConfiguration,
|
||||
streamDelegate: NIOHTTP2StreamDelegate? = nil,
|
||||
configuration: NIOHTTP2Handler.Configuration = .init(),
|
||||
position: ChannelPipeline.Position = .last,
|
||||
inboundStreamInitializer: @escaping NIOHTTP2Handler.StreamInitializerWithOutput<Output>
|
||||
inboundStreamInitializer: @escaping NIOChannelInitializerWithOutput<Output>
|
||||
) throws -> NIOHTTP2Handler.AsyncStreamMultiplexer<Output> {
|
||||
let handler = NIOHTTP2Handler(
|
||||
mode: mode,
|
||||
eventLoop: self.eventLoop,
|
||||
connectionConfiguration: connectionConfiguration,
|
||||
streamConfiguration: streamConfiguration,
|
||||
streamDelegate: streamDelegate,
|
||||
connectionConfiguration: configuration.connection,
|
||||
streamConfiguration: configuration.stream,
|
||||
inboundStreamInitializer: { channel in channel.eventLoop.makeSucceededVoidFuture() }
|
||||
)
|
||||
|
||||
@@ -677,55 +722,89 @@ extension ChannelPipeline.SynchronousOperations {
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - mode: The mode this pipeline will operate in, server or client.
|
||||
/// - inboundStreamAsyncChannelConfiguration: Settings relating to `NIOAsyncChannel`s wrapping internal stream channels.
|
||||
/// - connectionConfiguration: The settings that will be used when establishing the connection. These will be sent to the peer as part of the
|
||||
/// handshake.
|
||||
/// - streamConfiguration: The settings that will be used when establishing new streams. These mainly pertain to flow control.
|
||||
/// - streamDelegate: The delegate to be notified in the event of stream creation and close.
|
||||
/// - position: The position in the pipeline into which to insert the `NIOHTTP2Handler`.
|
||||
/// - inboundStreamBackpressureStrategy: The backpressure strategy of the ``NIOAsyncChannel``s wrapping inbound HTTP/2 streams.
|
||||
/// - isInboundStreamOutboundHalfClosureEnabled: If outbound half closure should be enabled for the ``NIOAsyncChannel``s wrapping inbound HTTP/2 streams.
|
||||
/// - streamInboundType: The ``NIOAsyncChannel/inboundStream`` message type for inbound stream channels.
|
||||
/// This type must match the `InboundOut` type of the final handler added to the stream channel by the `inboundStreamInitializer`
|
||||
/// or ``HTTP2Frame/FramePayload`` if there are none.
|
||||
/// - streamOutboundType: The ``NIOAsyncChannel/outboundWriter`` message type for inbound stream channels.
|
||||
/// This type must match the `OutboundIn` type of the final handler added to the stream channel by the `inboundStreamInitializer`
|
||||
/// or ``HTTP2Frame/FramePayload`` if there are none.
|
||||
/// - inboundStreamInitializer: A closure that will be called whenever the remote peer initiates a new stream.
|
||||
/// - Returns: An `EventLoopFuture` containing the `AsyncStreamMultiplexer` inserted into this pipeline which wraps
|
||||
/// inbound streams as `NIOAsyncChannels` after initialization. The multiplexer 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, *)
|
||||
@_spi(AsyncChannel)
|
||||
public func configureAsyncHTTP2Pipeline<StreamInbound, StreamOutbound>(
|
||||
internal func configureAsyncHTTP2Pipeline<StreamInbound, StreamOutbound>(
|
||||
mode: NIOHTTP2Handler.ParserMode,
|
||||
connectionConfiguration: NIOHTTP2Handler.ConnectionConfiguration,
|
||||
streamConfiguration: NIOHTTP2Handler.StreamConfiguration,
|
||||
streamDelegate: NIOHTTP2StreamDelegate? = nil,
|
||||
inboundStreamAsyncChannelConfiguration: NIOAsyncChannel<StreamInbound, StreamOutbound>.Configuration,
|
||||
connectionConfiguration: NIOHTTP2Handler.ConnectionConfiguration = .init(),
|
||||
streamConfiguration: NIOHTTP2Handler.StreamConfiguration = .init(),
|
||||
position: ChannelPipeline.Position = .last,
|
||||
inboundStreamBackpressureStrategy: NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark? = nil,
|
||||
isInboundStreamOutboundHalfClosureEnabled: Bool = false,
|
||||
streamInboundType: StreamInbound.Type = StreamInbound.self,
|
||||
streamOutboundType: StreamOutbound.Type = StreamOutbound.self,
|
||||
inboundStreamInitializer: @escaping NIOHTTP2Handler.StreamInitializer
|
||||
inboundStreamInitializer: @escaping NIOChannelInitializer
|
||||
) throws -> NIOHTTP2Handler.AsyncStreamMultiplexer<NIOAsyncChannel<StreamInbound, StreamOutbound>> {
|
||||
return try self.configureAsyncHTTP2Pipeline(
|
||||
mode: mode,
|
||||
connectionConfiguration: connectionConfiguration,
|
||||
streamConfiguration: streamConfiguration,
|
||||
streamDelegate: streamDelegate,
|
||||
configuration: .init(
|
||||
connection: connectionConfiguration,
|
||||
stream: streamConfiguration
|
||||
),
|
||||
position: position
|
||||
) { channel in
|
||||
inboundStreamInitializer(channel).flatMapThrowing { _ in
|
||||
return try NIOAsyncChannel(
|
||||
return try NIOAsyncChannel<StreamInbound, StreamOutbound>(
|
||||
synchronouslyWrapping: channel,
|
||||
configuration: .init(
|
||||
backpressureStrategy: inboundStreamBackpressureStrategy ?? .init(lowWatermark: 2, highWatermark: 10),
|
||||
isOutboundHalfClosureEnabled: isInboundStreamOutboundHalfClosureEnabled,
|
||||
inboundType: StreamInbound.self,
|
||||
outboundType: StreamOutbound.self
|
||||
)
|
||||
configuration: inboundStreamAsyncChannelConfiguration
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `NIONegotiatedHTTPVersion` is a generic negotiation result holder for HTTP/1.1 and HTTP/2
|
||||
@_spi(AsyncChannel)
|
||||
public enum NIONegotiatedHTTPVersion<HTTP1Output: Sendable, HTTP2Output: Sendable> {
|
||||
case http1_1(HTTP1Output)
|
||||
case http2(HTTP2Output)
|
||||
}
|
||||
|
||||
/// `NIOHTTP2AsyncConfiguration` contains all configuration required for setting up an HTTP/2 async connection.
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
@_spi(AsyncChannel)
|
||||
public struct NIOHTTP2AsyncConfiguration<HTTP2ConnectionInbound: Sendable, HTTP2ConnectionOutbound: Sendable, HTTP2StreamInbound: Sendable, HTTP2StreamOutbound: Sendable> {
|
||||
/// The settings that will be used when establishing new streams. These mainly pertain to flow control.
|
||||
public var connection: NIOHTTP2Handler.ConnectionConfiguration
|
||||
/// The settings that will be used when establishing the connection. These will be sent to the peer as part of the
|
||||
/// handshake.
|
||||
public var stream: NIOHTTP2Handler.StreamConfiguration
|
||||
|
||||
/// The settings for the `NIOAsyncChannel` wrapping the HTTP/2 connection channel
|
||||
public var connectionAsyncChannel: NIOAsyncChannel<HTTP2ConnectionInbound, HTTP2ConnectionOutbound>.Configuration
|
||||
/// The settings for `NIOAsyncChannel`s wrapping inbound HTTP/2 stream channels
|
||||
public var inboundStreamAsyncChannel: NIOAsyncChannel<HTTP2StreamInbound, HTTP2StreamOutbound>.Configuration
|
||||
|
||||
/// A callback used to configure the HTTP/2 connection channel
|
||||
public var connectionInitializer: NIOChannelInitializer
|
||||
/// A callback used to configure inbound HTTP/2 stream channels
|
||||
public var inboundStreamInitializer: NIOChannelInitializer
|
||||
|
||||
public init(
|
||||
connectionAsyncChannel: NIOAsyncChannel<HTTP2ConnectionInbound, HTTP2ConnectionOutbound>.Configuration,
|
||||
inboundStreamAsyncChannel: NIOAsyncChannel<HTTP2StreamInbound, HTTP2StreamOutbound>.Configuration,
|
||||
connection: NIOHTTP2Handler.ConnectionConfiguration = .init(),
|
||||
stream: NIOHTTP2Handler.StreamConfiguration = .init(),
|
||||
connectionInitializer: @escaping NIOChannelInitializer,
|
||||
inboundStreamInitializer: @escaping NIOChannelInitializer
|
||||
) {
|
||||
self.connectionAsyncChannel = connectionAsyncChannel
|
||||
self.inboundStreamAsyncChannel = inboundStreamAsyncChannel
|
||||
self.connection = connection
|
||||
self.stream = stream
|
||||
self.connectionInitializer = connectionInitializer
|
||||
self.inboundStreamInitializer = inboundStreamInitializer
|
||||
}
|
||||
}
|
||||
|
||||
#if swift(>=5.7)
|
||||
// Unchecked sendable because `NIOAsyncChannel.Configuration` is actually sendable but not yet marked as such
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
@_spi(AsyncChannel)
|
||||
extension NIOHTTP2AsyncConfiguration: @unchecked Sendable {}
|
||||
#endif
|
||||
@@ -230,7 +230,7 @@ final class HTTP2StreamChannel: Channel, ChannelCore {
|
||||
}
|
||||
}
|
||||
|
||||
internal func configure<Output>(initializer: @escaping NIOHTTP2Handler.StreamInitializerWithOutput<Output>, userPromise promise: EventLoopPromise<Output>?) {
|
||||
internal func configure<Output>(initializer: @escaping NIOChannelInitializerWithOutput<Output>, userPromise promise: EventLoopPromise<Output>?) {
|
||||
assert(self.streamDataType == .framePayload)
|
||||
// We need to configure this channel. This involves doing four things:
|
||||
// 1. Setting our autoRead state from the parent
|
||||
|
||||
@@ -106,7 +106,7 @@ extension MultiplexerAbstractChannel {
|
||||
self.baseChannel.configure(initializer: initializer, userPromise: promise)
|
||||
}
|
||||
|
||||
func configure<Output>(initializer: @escaping NIOHTTP2Handler.StreamInitializerWithOutput<Output>, userPromise promise: EventLoopPromise<Output>?) {
|
||||
func configure<Output>(initializer: @escaping NIOChannelInitializerWithOutput<Output>, userPromise promise: EventLoopPromise<Output>?) {
|
||||
self.baseChannel.configure(initializer: initializer, userPromise: promise)
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
|
||||
import XCTest
|
||||
|
||||
import NIOConcurrencyHelpers
|
||||
@_spi(AsyncChannel) import NIOCore
|
||||
import NIOEmbedded
|
||||
import NIOHPACK
|
||||
@@ -35,10 +36,12 @@ final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase {
|
||||
self.serverChannel = nil
|
||||
}
|
||||
|
||||
|
||||
static let requestFramePayload = HTTP2Frame.FramePayload.headers(.init(headers: HPACKHeaders([(":method", "GET"), (":authority", "localhost"), (":scheme", "https"), (":path", "/")]), endStream: true))
|
||||
static let responseFramePayload = HTTP2Frame.FramePayload.headers(.init(headers: HPACKHeaders([(":status", "200")]), endStream: true))
|
||||
|
||||
static let requestHead = HTTPRequestHead(version: .init(major: 1, minor: 1), method: .GET, uri: "/testHTTP1")
|
||||
static let responseHead = HTTPResponseHead(version: .init(major: 1, minor: 1), status: .ok, headers: HTTPHeaders([("transfer-encoding", "chunked")]))
|
||||
|
||||
final class OKResponder: ChannelInboundHandler {
|
||||
typealias InboundIn = HTTP2Frame.FramePayload
|
||||
typealias OutboundOut = HTTP2Frame.FramePayload
|
||||
@@ -57,6 +60,23 @@ final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
final class HTTP1OKResponder: ChannelInboundHandler {
|
||||
typealias InboundIn = HTTPServerRequestPart
|
||||
typealias OutboundOut = HTTPServerResponsePart
|
||||
|
||||
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
|
||||
switch self.unwrapInboundIn(data) {
|
||||
case .head:
|
||||
context.write(self.wrapOutboundOut(.head(responseHead)), promise: nil)
|
||||
context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil)
|
||||
case .body, .end:
|
||||
break
|
||||
}
|
||||
|
||||
context.fireChannelRead(data)
|
||||
}
|
||||
}
|
||||
|
||||
final class SimpleRequest: ChannelInboundHandler {
|
||||
typealias InboundIn = HTTP2Frame.FramePayload
|
||||
typealias OutboundOut = HTTP2Frame.FramePayload
|
||||
@@ -71,27 +91,21 @@ final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
// `testBasicPipelineCommunicates` ensures that a client-server system set up to use async stream abstractions
|
||||
// can communicate successfully.
|
||||
func testBasicPipelineCommunicates() async throws {
|
||||
let requestCount = 100
|
||||
|
||||
let serverRecorder = InboundFramePayloadRecorder()
|
||||
|
||||
let clientMultiplexer = try await assertNoThrowWithValue(
|
||||
try await self.clientChannel.configureAsyncHTTP2Pipeline(
|
||||
mode: .client,
|
||||
connectionConfiguration: .init(),
|
||||
streamConfiguration: .init()
|
||||
) { channel -> EventLoopFuture<Channel> in
|
||||
try await self.clientChannel.configureAsyncHTTP2Pipeline(mode: .client) { channel -> EventLoopFuture<Channel> in
|
||||
channel.eventLoop.makeSucceededFuture(channel)
|
||||
}.get()
|
||||
)
|
||||
|
||||
let serverMultiplexer = try await assertNoThrowWithValue(
|
||||
try await self.serverChannel.configureAsyncHTTP2Pipeline(
|
||||
mode: .server,
|
||||
connectionConfiguration: .init(),
|
||||
streamConfiguration: .init()
|
||||
) { channel -> EventLoopFuture<Channel> in
|
||||
try await self.serverChannel.configureAsyncHTTP2Pipeline(mode: .server) { channel -> EventLoopFuture<Channel> in
|
||||
channel.pipeline.addHandlers([OKResponder(), serverRecorder]).map { _ in channel }
|
||||
}.get()
|
||||
)
|
||||
@@ -118,7 +132,8 @@ final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase {
|
||||
}
|
||||
|
||||
let clientRecorder = try await streamChannel.pipeline.handler(type: InboundFramePayloadRecorder.self).get()
|
||||
try await self.interactInMemory(self.clientChannel, self.serverChannel)
|
||||
try await self.deliverAllBytes(from: self.clientChannel, to: self.serverChannel)
|
||||
try await self.deliverAllBytes(from: self.serverChannel, to: self.clientChannel)
|
||||
clientRecorder.receivedFrames.assertFramePayloadsMatch([ConfiguringPipelineAsyncMultiplexerTests.responseFramePayload])
|
||||
try await streamChannel.closeFuture.get()
|
||||
}
|
||||
@@ -133,39 +148,37 @@ final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase {
|
||||
serverRecorder.receivedFrames.assertFramePayloadsMatch(Array(repeating: ConfiguringPipelineAsyncMultiplexerTests.requestFramePayload, count: requestCount))
|
||||
}
|
||||
|
||||
// `testNIOAsyncConnectionStreamChannelPipelineCommunicates` ensures that a client-server system set up to use `NIOAsyncChannel`
|
||||
// wrappers around connection and stream channels can communicate successfully.
|
||||
func testNIOAsyncConnectionStreamChannelPipelineCommunicates() async throws {
|
||||
let requestCount = 100
|
||||
|
||||
let (clientAsyncChannel, clientMultiplexer) = try await assertNoThrowWithValue(
|
||||
try await self.clientChannel.configureAsyncHTTP2Pipeline(
|
||||
mode: .client,
|
||||
connectionConfiguration: .init(),
|
||||
streamConfiguration: .init(),
|
||||
connectionInboundType: HTTP2Frame.self,
|
||||
connectionOutboundType: HTTP2Frame.self,
|
||||
streamInboundType: HTTP2Frame.FramePayload.self,
|
||||
streamOutboundType: HTTP2Frame.FramePayload.self
|
||||
) { channel in
|
||||
channel.eventLoop.makeSucceededVoidFuture()
|
||||
} inboundStreamInitializer: { channel -> EventLoopFuture<Void> in
|
||||
channel.eventLoop.makeSucceededVoidFuture()
|
||||
}.get()
|
||||
configuration: .init(
|
||||
connectionAsyncChannel: NIOAsyncChannel.Configuration(inboundType: HTTP2Frame.self, outboundType: HTTP2Frame.self),
|
||||
inboundStreamAsyncChannel: NIOAsyncChannel.Configuration(inboundType: HTTP2Frame.FramePayload.self, outboundType: HTTP2Frame.FramePayload.self)
|
||||
) { channel in
|
||||
channel.eventLoop.makeSucceededVoidFuture()
|
||||
} inboundStreamInitializer: { channel -> EventLoopFuture<Void> in
|
||||
channel.eventLoop.makeSucceededVoidFuture()
|
||||
}
|
||||
).get()
|
||||
)
|
||||
|
||||
let (serverAsyncChannel, serverMultiplexer) = try await assertNoThrowWithValue(
|
||||
try await self.serverChannel.configureAsyncHTTP2Pipeline(
|
||||
mode: .server,
|
||||
connectionConfiguration: .init(),
|
||||
streamConfiguration: .init(),
|
||||
connectionInboundType: HTTP2Frame.self,
|
||||
connectionOutboundType: HTTP2Frame.self,
|
||||
streamInboundType: HTTP2Frame.FramePayload.self,
|
||||
streamOutboundType: HTTP2Frame.FramePayload.self
|
||||
) { channel in
|
||||
channel.eventLoop.makeSucceededVoidFuture()
|
||||
} inboundStreamInitializer: { channel -> EventLoopFuture<Void> in
|
||||
channel.eventLoop.makeSucceededVoidFuture()
|
||||
}.get()
|
||||
configuration: .init(
|
||||
connectionAsyncChannel: NIOAsyncChannel.Configuration(inboundType: HTTP2Frame.self, outboundType: HTTP2Frame.self),
|
||||
inboundStreamAsyncChannel: NIOAsyncChannel.Configuration(inboundType: HTTP2Frame.FramePayload.self, outboundType: HTTP2Frame.FramePayload.self)
|
||||
) { channel in
|
||||
channel.eventLoop.makeSucceededVoidFuture()
|
||||
} inboundStreamInitializer: { channel -> EventLoopFuture<Void> in
|
||||
channel.eventLoop.makeSucceededVoidFuture()
|
||||
}
|
||||
).get()
|
||||
)
|
||||
|
||||
try await assertNoThrow(try await self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel))
|
||||
@@ -181,7 +194,7 @@ final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase {
|
||||
try await streamChannel.outboundWriter.write(ConfiguringPipelineAsyncMultiplexerTests.responseFramePayload)
|
||||
streamChannel.outboundWriter.finish()
|
||||
|
||||
try await self.interactInMemory(self.clientChannel, self.serverChannel)
|
||||
try await self.deliverAllBytes(from: self.serverChannel, to: self.clientChannel)
|
||||
}
|
||||
serverInboundChannelCount += 1
|
||||
}
|
||||
@@ -202,7 +215,7 @@ final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase {
|
||||
try await streamChannel.outboundWriter.write(ConfiguringPipelineAsyncMultiplexerTests.requestFramePayload)
|
||||
streamChannel.outboundWriter.finish()
|
||||
|
||||
try await self.interactInMemory(self.clientChannel, self.serverChannel)
|
||||
try await self.deliverAllBytes(from: self.clientChannel, to: self.serverChannel)
|
||||
|
||||
for try await receivedFrame in streamChannel.inboundStream {
|
||||
receivedFrame.assertFramePayloadMatches(this: ConfiguringPipelineAsyncMultiplexerTests.responseFramePayload)
|
||||
@@ -219,49 +232,53 @@ final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase {
|
||||
XCTAssertEqual(serverInboundChannelCount, requestCount, "We should have created one server-side channel as a result of the one HTTP/2 stream used.")
|
||||
}
|
||||
}
|
||||
|
||||
func testNIOAsyncStreamChannelPipelineCommunicates() async throws {
|
||||
|
||||
// `testNegotiatedHTTP2BasicPipelineCommunicates` ensures that a client-server system set up to use async stream abstractions
|
||||
// can communicate successfully when HTTP/2 is negotiated.
|
||||
func testNegotiatedHTTP2BasicPipelineCommunicates() async throws {
|
||||
let requestCount = 100
|
||||
|
||||
let serverRecorder = InboundFramePayloadRecorder()
|
||||
|
||||
let clientMultiplexer = try await assertNoThrowWithValue(
|
||||
try await self.clientChannel.configureAsyncHTTP2Pipeline(
|
||||
mode: .client,
|
||||
connectionConfiguration: .init(),
|
||||
streamConfiguration: .init(),
|
||||
streamInboundType: HTTP2Frame.FramePayload.self,
|
||||
streamOutboundType: HTTP2Frame.FramePayload.self
|
||||
) { channel -> EventLoopFuture<Void> in
|
||||
channel.eventLoop.makeSucceededVoidFuture()
|
||||
try await self.clientChannel.configureAsyncHTTP2Pipeline(mode: .client) { channel -> EventLoopFuture<Channel> in
|
||||
channel.eventLoop.makeSucceededFuture(channel)
|
||||
}.get()
|
||||
)
|
||||
|
||||
let serverMultiplexer = try await assertNoThrowWithValue(
|
||||
try await self.serverChannel.configureAsyncHTTP2Pipeline(
|
||||
mode: .server,
|
||||
connectionConfiguration: .init(),
|
||||
streamConfiguration: .init(),
|
||||
streamInboundType: HTTP2Frame.FramePayload.self,
|
||||
streamOutboundType: HTTP2Frame.FramePayload.self
|
||||
) { channel -> EventLoopFuture<Void> in
|
||||
channel.eventLoop.makeSucceededVoidFuture()
|
||||
}.get()
|
||||
)
|
||||
let nioProtocolNegotiationHandler = try await self.serverChannel.configureAsyncHTTPServerPipeline() { channel in
|
||||
channel.eventLoop.makeSucceededVoidFuture()
|
||||
} http2ConnectionInitializer: { channel in
|
||||
channel.eventLoop.makeSucceededVoidFuture()
|
||||
} http2InboundStreamInitializer: { channel -> EventLoopFuture<Channel> in
|
||||
channel.pipeline.addHandlers([OKResponder(), serverRecorder]).map { _ in channel }
|
||||
}.get()
|
||||
|
||||
// Let's pretend the TLS handler did protocol negotiation for us
|
||||
self.serverChannel.pipeline.fireUserInboundEventTriggered(TLSUserEvent.handshakeCompleted(negotiatedProtocol: "h2"))
|
||||
|
||||
let nioProtocolNegotiationResult = try await nioProtocolNegotiationHandler.protocolNegotiationResult.get()
|
||||
|
||||
try await assertNoThrow(try await self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel))
|
||||
|
||||
let serverMultiplexer: NIOHTTP2Handler.AsyncStreamMultiplexer<Channel>
|
||||
switch nioProtocolNegotiationResult {
|
||||
case .deferredResult:
|
||||
preconditionFailure("Negotiation result must be ready")
|
||||
case .finished(let negotiationResult):
|
||||
switch negotiationResult {
|
||||
case .http1_1:
|
||||
preconditionFailure("Negotiation result must be ready")
|
||||
case .http2(let (_, multiplexer)):
|
||||
serverMultiplexer = multiplexer
|
||||
}
|
||||
}
|
||||
|
||||
try await withThrowingTaskGroup(of: Int.self, returning: Void.self) { group in
|
||||
// server
|
||||
group.addTask {
|
||||
var serverInboundChannelCount = 0
|
||||
for try await streamChannel in serverMultiplexer.inbound {
|
||||
for try await receivedFrame in streamChannel.inboundStream {
|
||||
receivedFrame.assertFramePayloadMatches(this: ConfiguringPipelineAsyncMultiplexerTests.requestFramePayload)
|
||||
|
||||
try await streamChannel.outboundWriter.write(ConfiguringPipelineAsyncMultiplexerTests.responseFramePayload)
|
||||
streamChannel.outboundWriter.finish()
|
||||
|
||||
try await self.interactInMemory(self.clientChannel, self.serverChannel)
|
||||
}
|
||||
for try await _ in serverMultiplexer.inbound {
|
||||
serverInboundChannelCount += 1
|
||||
}
|
||||
return serverInboundChannelCount
|
||||
@@ -269,30 +286,169 @@ final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase {
|
||||
|
||||
// client
|
||||
for _ in 0 ..< requestCount {
|
||||
let streamChannel = try await clientMultiplexer.createStreamChannel(
|
||||
configuration: .init(
|
||||
inboundType: HTTP2Frame.FramePayload.self,
|
||||
outboundType: HTTP2Frame.FramePayload.self
|
||||
)
|
||||
) { channel -> EventLoopFuture<Void> in
|
||||
channel.eventLoop.makeSucceededVoidFuture()
|
||||
}
|
||||
// Let's try sending some requests
|
||||
try await streamChannel.outboundWriter.write(ConfiguringPipelineAsyncMultiplexerTests.requestFramePayload)
|
||||
streamChannel.outboundWriter.finish()
|
||||
|
||||
try await self.interactInMemory(self.clientChannel, self.serverChannel)
|
||||
|
||||
for try await receivedFrame in streamChannel.inboundStream {
|
||||
receivedFrame.assertFramePayloadMatches(this: ConfiguringPipelineAsyncMultiplexerTests.responseFramePayload)
|
||||
let streamChannel = try await clientMultiplexer.createStreamChannel { channel -> EventLoopFuture<Channel> in
|
||||
return channel.pipeline.addHandlers([SimpleRequest(), InboundFramePayloadRecorder()]).map {
|
||||
return channel
|
||||
}
|
||||
}
|
||||
|
||||
let clientRecorder = try await streamChannel.pipeline.handler(type: InboundFramePayloadRecorder.self).get()
|
||||
|
||||
try await self.deliverAllBytes(from: self.clientChannel, to: self.serverChannel)
|
||||
try await self.deliverAllBytes(from: self.serverChannel, to: self.clientChannel)
|
||||
|
||||
clientRecorder.receivedFrames.assertFramePayloadsMatch([ConfiguringPipelineAsyncMultiplexerTests.responseFramePayload])
|
||||
try await streamChannel.closeFuture.get()
|
||||
}
|
||||
|
||||
try await assertNoThrow(try await self.clientChannel.finish())
|
||||
try await assertNoThrow(try await self.serverChannel.finish())
|
||||
|
||||
let serverInboundChannelCount = try await assertNoThrowWithValue(try await group.next()!)
|
||||
XCTAssertEqual(serverInboundChannelCount, requestCount, "We should have created one server-side channel as a result of the one HTTP/2 stream used.")
|
||||
XCTAssertEqual(serverInboundChannelCount, requestCount, "We should have created one server-side channel as a result of the each HTTP/2 stream used.")
|
||||
}
|
||||
|
||||
serverRecorder.receivedFrames.assertFramePayloadsMatch(Array(repeating: ConfiguringPipelineAsyncMultiplexerTests.requestFramePayload, count: requestCount))
|
||||
}
|
||||
|
||||
// `testNegotiatedHTTP1BasicPipelineCommunicates` ensures that a client-server system set up to use async stream abstractions
|
||||
// can communicate successfully when HTTP/1.1 is negotiated.
|
||||
func testNegotiatedHTTP1BasicPipelineCommunicates() async throws {
|
||||
let requestCount = 100
|
||||
|
||||
let _ = try await self.clientChannel.pipeline.addHTTPClientHandlers().map { _ in
|
||||
self.clientChannel.pipeline.addHandlers([InboundRecorderHandler<HTTPClientResponsePart>(), HTTP1ClientSendability()])
|
||||
}.get()
|
||||
|
||||
let nioProtocolNegotiationHandler = try await self.serverChannel.configureAsyncHTTPServerPipeline() { channel in
|
||||
channel.pipeline.addHandlers([HTTP1OKResponder(), InboundRecorderHandler<HTTPServerRequestPart>()])
|
||||
} http2ConnectionInitializer: { channel in
|
||||
channel.eventLoop.makeSucceededVoidFuture()
|
||||
} http2InboundStreamInitializer: { channel -> EventLoopFuture<Channel> in
|
||||
channel.eventLoop.makeSucceededFuture(channel)
|
||||
}.get()
|
||||
|
||||
// Let's pretend the TLS handler did protocol negotiation for us
|
||||
self.serverChannel.pipeline.fireUserInboundEventTriggered(TLSUserEvent.handshakeCompleted(negotiatedProtocol: "http/1.1"))
|
||||
|
||||
let nioProtocolNegotiationResult = try await nioProtocolNegotiationHandler.protocolNegotiationResult.get()
|
||||
|
||||
try await self.deliverAllBytes(from: self.clientChannel, to: self.serverChannel)
|
||||
try await self.deliverAllBytes(from: self.serverChannel, to: self.clientChannel)
|
||||
|
||||
switch nioProtocolNegotiationResult {
|
||||
case .deferredResult:
|
||||
preconditionFailure("Negotiation result must be ready")
|
||||
case .finished(let negotiationResult):
|
||||
switch negotiationResult {
|
||||
case .http1_1:
|
||||
break
|
||||
case .http2:
|
||||
preconditionFailure("Negotiation result must be http/1.1")
|
||||
}
|
||||
}
|
||||
|
||||
// client
|
||||
for _ in 0 ..< requestCount {
|
||||
// Let's try sending some http/1.1 requests.
|
||||
// we need to put these through a mapping to remove references to `IOData` which isn't Sendable
|
||||
try await self.clientChannel.writeOutbound(HTTP1ClientSendability.RequestPart.head(ConfiguringPipelineAsyncMultiplexerTests.requestHead))
|
||||
try await self.clientChannel.writeOutbound(HTTP1ClientSendability.RequestPart.end(nil))
|
||||
try await self.deliverAllBytes(from: self.clientChannel, to: self.serverChannel)
|
||||
try await self.deliverAllBytes(from: self.serverChannel, to: self.clientChannel)
|
||||
}
|
||||
|
||||
// check expectations
|
||||
let clientRecorder = try await self.clientChannel.pipeline.handler(type: InboundRecorderHandler<HTTPClientResponsePart>.self).get()
|
||||
let serverRecorder = try await self.serverChannel.pipeline.handler(type: InboundRecorderHandler<HTTPServerRequestPart>.self).get()
|
||||
|
||||
XCTAssertEqual(serverRecorder.receivedParts.count, requestCount*2)
|
||||
XCTAssertEqual(clientRecorder.receivedParts.count, requestCount*2)
|
||||
|
||||
for i in 0 ..< requestCount {
|
||||
XCTAssertEqual(serverRecorder.receivedParts[i*2], HTTPServerRequestPart.head(ConfiguringPipelineAsyncMultiplexerTests.requestHead), "Unexpected request part in iteration \(i)")
|
||||
XCTAssertEqual(serverRecorder.receivedParts[i*2+1], HTTPServerRequestPart.end(nil), "Unexpected request part in iteration \(i)")
|
||||
|
||||
XCTAssertEqual(clientRecorder.receivedParts[i*2], HTTPClientResponsePart.head(ConfiguringPipelineAsyncMultiplexerTests.responseHead), "Unexpected response part in iteration \(i)")
|
||||
XCTAssertEqual(clientRecorder.receivedParts[i*2+1], HTTPClientResponsePart.end(nil), "Unexpected response part in iteration \(i)")
|
||||
}
|
||||
|
||||
try await assertNoThrow(try await self.clientChannel.finish())
|
||||
try await assertNoThrow(try await self.serverChannel.finish())
|
||||
}
|
||||
|
||||
// Simple handler which maps client request parts to remove references to `IOData` which isn't Sendable
|
||||
internal final class HTTP1ClientSendability: ChannelOutboundHandler {
|
||||
public typealias RequestPart = HTTPPart<HTTPRequestHead, ByteBuffer>
|
||||
|
||||
typealias OutboundIn = RequestPart
|
||||
typealias OutboundOut = HTTPClientRequestPart
|
||||
|
||||
func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
|
||||
let requestPart = self.unwrapOutboundIn(data)
|
||||
|
||||
let httpClientRequestPart: HTTPClientRequestPart
|
||||
switch requestPart {
|
||||
case .head(let head):
|
||||
httpClientRequestPart = .head(head)
|
||||
case .body(let byteBuffer):
|
||||
httpClientRequestPart = .body(.byteBuffer(byteBuffer))
|
||||
case .end(let headers):
|
||||
httpClientRequestPart = .end(headers)
|
||||
}
|
||||
|
||||
context.write(self.wrapOutboundOut(httpClientRequestPart), promise: promise)
|
||||
}
|
||||
}
|
||||
|
||||
// Simple handler which maps server response parts to remove references to `IOData` which isn't Sendable
|
||||
internal final class HTTP1ServerSendability: ChannelOutboundHandler {
|
||||
public typealias ResponsePart = HTTPPart<HTTPResponseHead, ByteBuffer>
|
||||
|
||||
typealias OutboundIn = ResponsePart
|
||||
typealias OutboundOut = HTTPServerResponsePart
|
||||
|
||||
func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
|
||||
let responsePart = self.unwrapOutboundIn(data)
|
||||
|
||||
let httpServerResponsePart: HTTPServerResponsePart
|
||||
switch responsePart {
|
||||
case .head(let head):
|
||||
httpServerResponsePart = .head(head)
|
||||
case .body(let byteBuffer):
|
||||
httpServerResponsePart = .body(.byteBuffer(byteBuffer))
|
||||
case .end(let headers):
|
||||
httpServerResponsePart = .end(headers)
|
||||
}
|
||||
|
||||
context.write(self.wrapOutboundOut(httpServerResponsePart), promise: promise)
|
||||
}
|
||||
}
|
||||
|
||||
/// A simple channel handler that records inbound messages.
|
||||
internal final class InboundRecorderHandler<message>: ChannelInboundHandler, @unchecked Sendable {
|
||||
typealias InboundIn = message
|
||||
|
||||
private let partsLock = NIOLock()
|
||||
private var _receivedParts: [message] = []
|
||||
|
||||
var receivedParts: [message] {
|
||||
get {
|
||||
self.partsLock.withLock {
|
||||
self._receivedParts
|
||||
}
|
||||
}
|
||||
set {
|
||||
self.partsLock.withLock {
|
||||
self._receivedParts = newValue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
|
||||
self.receivedParts.append(self.unwrapInboundIn(data))
|
||||
context.fireChannelRead(data)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,6 +64,8 @@ extension XCTestCase {
|
||||
|
||||
/// Have two `NIOAsyncTestingChannel` objects send and receive data from each other until
|
||||
/// they make no forward progress.
|
||||
///
|
||||
/// ** This function is racy and can lead to deadlocks, prefer the one-way variant which is less error-prone**
|
||||
func interactInMemory(_ first: NIOAsyncTestingChannel, _ second: NIOAsyncTestingChannel, file: StaticString = #filePath, line: UInt = #line) async throws {
|
||||
var operated: Bool
|
||||
|
||||
@@ -85,6 +87,23 @@ extension XCTestCase {
|
||||
} while operated
|
||||
}
|
||||
|
||||
/// Have a `NIOAsyncTestingChannel` send data to another until it makes no forward progress.
|
||||
func deliverAllBytes(from source: NIOAsyncTestingChannel, to destination: NIOAsyncTestingChannel, file: StaticString = #filePath, line: UInt = #line) async throws {
|
||||
var operated: Bool
|
||||
|
||||
func readBytesFromChannel(_ channel: NIOAsyncTestingChannel) async -> ByteBuffer? {
|
||||
return try? await assertNoThrowWithValue(await channel.readOutbound(as: ByteBuffer.self))
|
||||
}
|
||||
|
||||
repeat {
|
||||
operated = false
|
||||
if let data = await readBytesFromChannel(source) {
|
||||
operated = true
|
||||
try await assertNoThrow(try await destination.writeInbound(data), file: file, line: line)
|
||||
}
|
||||
} while operated
|
||||
}
|
||||
|
||||
/// Deliver all the bytes currently flushed on `sourceChannel` to `targetChannel`.
|
||||
func deliverAllBytes(from sourceChannel: EmbeddedChannel, to targetChannel: EmbeddedChannel, file: StaticString = #filePath, line: UInt = #line) {
|
||||
// Collect the serialized data.
|
||||
@@ -921,6 +940,18 @@ internal func assertNil(
|
||||
XCTAssertNil(result, file: file, line: line)
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
internal func assertEqual<T: Equatable>(
|
||||
_ expression1: @autoclosure () async throws -> T?,
|
||||
_ expression2: @autoclosure () async throws -> T?,
|
||||
file: StaticString = #filePath,
|
||||
line: UInt = #line
|
||||
) async rethrows {
|
||||
let result1 = try await expression1()
|
||||
let result2 = try await expression2()
|
||||
XCTAssertEqual(result1, result2, file: file, line: line)
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
internal func assertThrowsError<T>(
|
||||
_ expression: @autoclosure () async throws -> T,
|
||||
|
||||
Reference in new issue
Block a user