diff --git a/Package.swift b/Package.swift index ceaf294..41cc32a 100644 --- a/Package.swift +++ b/Package.swift @@ -69,6 +69,7 @@ let package = Package( .product(name: "NIOEmbedded", package: "swift-nio"), .product(name: "NIOHTTP1", package: "swift-nio"), .product(name: "NIOFoundationCompat", package: "swift-nio"), + .product(name: "Atomics", package: "swift-atomics"), ]), .testTarget( name: "NIOHPACKTests", diff --git a/Package@swift-5.5.swift b/Package@swift-5.5.swift index b060154..fde79d8 100644 --- a/Package@swift-5.5.swift +++ b/Package@swift-5.5.swift @@ -68,6 +68,7 @@ let package = Package( .product(name: "NIOEmbedded", package: "swift-nio"), .product(name: "NIOHTTP1", package: "swift-nio"), .product(name: "NIOFoundationCompat", package: "swift-nio"), + .product(name: "Atomics", package: "swift-atomics"), ]), .testTarget( name: "NIOHPACKTests", diff --git a/Sources/NIOHTTP2/HTTP2ChannelHandler+InboundStreamMultiplexer.swift b/Sources/NIOHTTP2/HTTP2ChannelHandler+InboundStreamMultiplexer.swift index 58656bb..63c7a76 100644 --- a/Sources/NIOHTTP2/HTTP2ChannelHandler+InboundStreamMultiplexer.swift +++ b/Sources/NIOHTTP2/HTTP2ChannelHandler+InboundStreamMultiplexer.swift @@ -36,76 +36,115 @@ internal protocol HTTP2InboundStreamMultiplexer { } extension NIOHTTP2Handler { - /// Abstracts over the integrated stream multiplexing (new) and the chained channel handler (legacy) multiplexing approaches. + /// Abstracts over the integrated stream multiplexing (inline) and the chained channel handler (legacy) multiplexing approaches. /// /// We use an enum for this purpose since we can't use a generic (for API compatibility reasons) and it allows us to avoid the cost of using an existential. internal enum InboundStreamMultiplexer: HTTP2InboundStreamMultiplexer { case legacy(LegacyInboundStreamMultiplexer) - case new + case inline(InlineStreamMultiplexer) func receivedFrame(_ frame: HTTP2Frame) { switch self { - case .legacy(let demultiplexer): - demultiplexer.receivedFrame(frame) - case .new: - fatalError("Not yet implemented.") + case .legacy(let legacyInboundStreamMultiplexer): + legacyInboundStreamMultiplexer.receivedFrame(frame) + case .inline(let inlineStreamMultiplexer): + inlineStreamMultiplexer.receivedFrame(frame) } } func streamError(streamID: HTTP2StreamID, error: Error) { switch self { - case .legacy(let demultiplexer): - demultiplexer.streamError(streamID: streamID, error: error) - case .new: - fatalError("Not yet implemented.") + case .legacy(let legacyInboundStreamMultiplexer): + legacyInboundStreamMultiplexer.streamError(streamID: streamID, error: error) + case .inline(let inlineStreamMultiplexer): + inlineStreamMultiplexer.streamError(streamID: streamID, error: error) } } func streamCreated(event: NIOHTTP2StreamCreatedEvent) { switch self { - case .legacy(let demultiplexer): - demultiplexer.streamCreated(event: event) - case .new: - fatalError("Not yet implemented.") + case .legacy(let legacyInboundStreamMultiplexer): + legacyInboundStreamMultiplexer.streamCreated(event: event) + case .inline(let inlineStreamMultiplexer): + inlineStreamMultiplexer.streamCreated(event: event) } } func streamClosed(event: StreamClosedEvent) { switch self { - case .legacy(let demultiplexer): - demultiplexer.streamClosed(event: event) - case .new: - fatalError("Not yet implemented.") + case .legacy(let legacyInboundStreamMultiplexer): + legacyInboundStreamMultiplexer.streamClosed(event: event) + case .inline(let inlineStreamMultiplexer): + inlineStreamMultiplexer.streamClosed(event: event) } } func streamWindowUpdated(event: NIOHTTP2WindowUpdatedEvent) { switch self { - case .legacy(let demultiplexer): - demultiplexer.streamWindowUpdated(event: event) - case .new: - fatalError("Not yet implemented.") + case .legacy(let legacyInboundStreamMultiplexer): + legacyInboundStreamMultiplexer.streamWindowUpdated(event: event) + case .inline(let inlineStreamMultiplexer): + inlineStreamMultiplexer.streamWindowUpdated(event: event) } } func initialStreamWindowChanged(event: NIOHTTP2BulkStreamWindowChangeEvent) { switch self { - case .legacy(let demultiplexer): - demultiplexer.initialStreamWindowChanged(event: event) - case .new: - fatalError("Not yet implemented.") + case .legacy(let legacyInboundStreamMultiplexer): + legacyInboundStreamMultiplexer.initialStreamWindowChanged(event: event) + case .inline(let inlineStreamMultiplexer): + inlineStreamMultiplexer.initialStreamWindowChanged(event: event) } } } } +extension NIOHTTP2Handler.InboundStreamMultiplexer { + func channelActiveReceived() { + switch self { + case .inline(let inlineStreamMultiplexer): + inlineStreamMultiplexer.propagateChannelActive() + case .legacy: + break // do nothing + } + } + + func channelInactiveReceived() { + switch self { + case .inline(let inlineStreamMultiplexer): + inlineStreamMultiplexer.propagateChannelInactive() + case .legacy: + break // do nothing + } + } + + func channelWritabilityChangedReceived() { + switch self { + case .inline(let inlineStreamMultiplexer): + inlineStreamMultiplexer.propagateChannelWritabilityChanged() + case .legacy: + break // do nothing + } + } + + func channelReadCompleteReceived() { + switch self { + case .inline(let inlineStreamMultiplexer): + inlineStreamMultiplexer.propagateReadComplete() + case .legacy: + break // do nothing + } + } +} + /// Provides an inbound stream multiplexer interface for legacy compatibility. /// -/// This doesn't actually do any demultiplexing of inbound streams but communicates with the `HTTP2StreamChannel` which does - mostly via `UserInboundEvent`s. +/// This doesn't actually do any demultiplexing of inbound streams but communicates with the `HTTP2StreamChannel` which does - mostly via user inbound events. internal struct LegacyInboundStreamMultiplexer { let context: ChannelHandlerContext } + extension LegacyInboundStreamMultiplexer: HTTP2InboundStreamMultiplexer { func receivedFrame(_ frame: HTTP2Frame) { self.context.fireChannelRead(NIOAny(frame)) diff --git a/Sources/NIOHTTP2/HTTP2ChannelHandler+InlineStreamMultiplexer.swift b/Sources/NIOHTTP2/HTTP2ChannelHandler+InlineStreamMultiplexer.swift new file mode 100644 index 0000000..c98c3a8 --- /dev/null +++ b/Sources/NIOHTTP2/HTTP2ChannelHandler+InlineStreamMultiplexer.swift @@ -0,0 +1,194 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2023 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import NIOCore + +internal struct InlineStreamMultiplexer { + private let context: ChannelHandlerContext + + private let commonStreamMultiplexer: HTTP2CommonInboundStreamMultiplexer + private let outboundView: NIOHTTP2Handler.OutboundView + + /// The delegate to be notified upon stream creation and close. + private var streamDelegate: NIOHTTP2StreamDelegate? + + init(context: ChannelHandlerContext, outboundView: NIOHTTP2Handler.OutboundView, mode: NIOHTTP2Handler.ParserMode, inboundStreamStateInitializer: MultiplexerAbstractChannel.InboundStreamStateInitializer, targetWindowSize: Int, streamChannelOutboundBytesHighWatermark: Int, streamChannelOutboundBytesLowWatermark: Int, streamDelegate: NIOHTTP2StreamDelegate?) { + self.context = context + self.commonStreamMultiplexer = HTTP2CommonInboundStreamMultiplexer( + mode: mode, + channel: context.channel, + inboundStreamStateInitializer: inboundStreamStateInitializer, + targetWindowSize: targetWindowSize, + streamChannelOutboundBytesHighWatermark: streamChannelOutboundBytesHighWatermark, + streamChannelOutboundBytesLowWatermark: streamChannelOutboundBytesLowWatermark + ) + self.outboundView = outboundView + } +} + +extension InlineStreamMultiplexer: HTTP2InboundStreamMultiplexer { + func receivedFrame(_ frame: HTTP2Frame) { + self.commonStreamMultiplexer.receivedFrame(frame, context: self.context, multiplexer: .inline(self)) + } + + func streamError(streamID: HTTP2StreamID, error: Error) { + let streamError = NIOHTTP2Errors.streamError(streamID: streamID, baseError: error) + self.commonStreamMultiplexer.streamError(context: self.context, streamError) + } + + func streamCreated(event: NIOHTTP2StreamCreatedEvent) { + self.commonStreamMultiplexer.streamCreated(event: event) + } + + func streamClosed(event: StreamClosedEvent) { + self.commonStreamMultiplexer.streamClosed(event: event) + } + + func streamWindowUpdated(event: NIOHTTP2WindowUpdatedEvent) { + if event.streamID == .rootStream { + // This force-unwrap is safe: we always have a connection window. + self.newConnectionWindowSize(newSize: event.inboundWindowSize!) + } else { + self.commonStreamMultiplexer.childStreamWindowUpdated(event: event) + } + } + + func initialStreamWindowChanged(event: NIOHTTP2BulkStreamWindowChangeEvent) { + self.commonStreamMultiplexer.initialStreamWindowChanged(event: event) + } + + private func newConnectionWindowSize(newSize: Int) { + guard let increment = self.commonStreamMultiplexer.newConnectionWindowSize(newSize) else { + return + } + + let frame = HTTP2Frame(streamID: .rootStream, payload: .windowUpdate(windowSizeIncrement: increment)) + self.writeFrame(frame, promise: nil) + self.flushStream(frame.streamID) + } +} + +extension InlineStreamMultiplexer: HTTP2OutboundStreamMultiplexer { + func writeFrame(_ frame: HTTP2Frame, promise: NIOCore.EventLoopPromise?) { + self.outboundView.write(context: self.context, frame: frame, promise: promise) + } + + func flushStream(_ id: HTTP2StreamID) { + switch self.commonStreamMultiplexer.flushDesired() { + case .proceed: + self.outboundView.flush(context: self.context) + case .waitForReadsToComplete: + break // flush will be executed on `readComplete` + } + } + + func requestStreamID(forChannel channel: NIOCore.Channel) -> HTTP2StreamID { + self.commonStreamMultiplexer.requestStreamID(forChannel: channel) + } + + func streamClosed(channelID: ObjectIdentifier) { + self.commonStreamMultiplexer.childChannelClosed(channelID: channelID) + } + + func streamClosed(id: HTTP2StreamID) { + self.commonStreamMultiplexer.childChannelClosed(streamID: id) + } +} + +extension InlineStreamMultiplexer { + internal func propagateChannelActive() { + self.commonStreamMultiplexer.propagateChannelActive(context: self.context) + } + + internal func propagateChannelInactive() { + self.commonStreamMultiplexer.propagateChannelInactive() + } + + internal func propagateChannelWritabilityChanged() { + self.commonStreamMultiplexer.propagateChannelWritabilityChanged(context: self.context) + } + + internal func propagateReadComplete() { + switch self.commonStreamMultiplexer.propagateReadComplete() { + case .flushNow: + // we had marked a flush as blocked by an active read which we may now perform + self.outboundView.flush(context: self.context) + case .noop: + break + } + } +} + +extension InlineStreamMultiplexer { + internal func createStreamChannel(promise: EventLoopPromise?, _ streamStateInitializer: @escaping (Channel) -> EventLoopFuture) { + self.commonStreamMultiplexer.createStreamChannel(multiplexer: .inline(self), promise: promise, streamStateInitializer) + } + + internal func createStreamChannel(_ streamStateInitializer: @escaping (Channel) -> EventLoopFuture) -> EventLoopFuture { + self.commonStreamMultiplexer.createStreamChannel(multiplexer: .inline(self), streamStateInitializer) + } +} + +extension NIOHTTP2Handler { + /// A multiplexer that creates a child channel for each HTTP/2 stream. + /// + /// > Note: This multiplexer is functionally similar to the ``HTTP2StreamMultiplexer`` channel handler, however as it is part of the ``NIOHTTP2Handler`` rather than a separate handler in the pipeline it benefits from efficiencies allowing for higher performance. + /// + /// 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`. + public struct StreamMultiplexer: @unchecked Sendable { + // '@unchecked Sendable' because this state is not intrinsically `Sendable` + // but it is only accessed in `createStreamChannel` which executes the work on the right event loop + private let inlineStreamMultiplexer: InlineStreamMultiplexer + + /// Cannot be created by users. + internal init(_ inlineStreamMultiplexer: InlineStreamMultiplexer) { + self.inlineStreamMultiplexer = inlineStreamMultiplexer + } + + /// Create a new `Channel` for a new stream initiated by this peer. + /// + /// This method is intended for situations where the NIO application is initiating the stream. For clients, + /// this is for all request streams. For servers, this is for pushed streams. + /// + /// > Note: Resources for the stream will be freed after it has been closed. + /// + /// - parameters: + /// - promise: An `EventLoopPromise` that will be succeeded with the new activated channel, or + /// failed if an error occurs. + /// - streamStateInitializer: A callback that will be invoked to allow you to configure the + /// `ChannelPipeline` for the newly created channel. + public func createStreamChannel(promise: EventLoopPromise?, _ streamStateInitializer: @escaping StreamInitializer) { + self.inlineStreamMultiplexer.createStreamChannel(promise: promise, streamStateInitializer) + } + + /// Create a new `Channel` for a new stream initiated by this peer. + /// + /// This method is intended for situations where the NIO application is initiating the stream. For clients, + /// this is for all request streams. For servers, this is for pushed streams. + /// + /// > Note: Resources for the stream will be freed after it has been closed. + /// + /// - Parameter streamStateInitializer: A callback that will be invoked to allow you to configure the + /// `ChannelPipeline` for the newly created channel. + /// - Returns: An `EventLoopFuture` containing the created `Channel`, fulfilled after the supplied `streamStateInitializer` has been executed on it. + public func createStreamChannel(_ streamStateInitializer: @escaping StreamInitializer) -> EventLoopFuture { + self.inlineStreamMultiplexer.createStreamChannel(streamStateInitializer) + } + } +} diff --git a/Sources/NIOHTTP2/HTTP2ChannelHandler.swift b/Sources/NIOHTTP2/HTTP2ChannelHandler.swift index bee0702..76e1760 100644 --- a/Sources/NIOHTTP2/HTTP2ChannelHandler.swift +++ b/Sources/NIOHTTP2/HTTP2ChannelHandler.swift @@ -40,6 +40,9 @@ public final class NIOHTTP2Handler: ChannelDuplexHandler { /// The magic string sent by clients at the start of a HTTP/2 connection. private static let clientMagic: StaticString = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n" + /// The event loop on which this handler will do work. + private let eventLoop: EventLoop? + /// The connection state machine. We always have one of these. private var stateMachine: HTTP2ConnectionStateMachine @@ -99,8 +102,58 @@ public final class NIOHTTP2Handler: ChannelDuplexHandler { /// trigger them. private let tolerateImpossibleStateTransitionsInDebugMode: Bool - /// The delegate for (de)multiplexing inbound streams. Set on `handlerAdded` and `nil`-ed out on `handlerRemoved`. - private var inboundStreamMultiplexer: InboundStreamMultiplexer? + /// The delegate for (de)multiplexing inbound streams. + private var inboundStreamMultiplexerState: InboundStreamMultiplexerState + internal var inboundStreamMultiplexer: InboundStreamMultiplexer? { + return self.inboundStreamMultiplexerState.multiplexer + } + + /// Holds and tracks the state of the ``InboundStreamMultiplexer``. + /// + /// It has three states to allow us to stash the config required for the 'inline' case without cluttering the ``NIOHTTP2Handler`` + /// - For legacy multiplexing this begins as`.uninitializedLegacy`, becomes `.initialized` on `handlerAdded` and moves to to `.deinitialized` on `handlerRemoved`. + /// - For inline multiplexing the behavior is the same with the modification that it begins as `.uninitializedInline` state when the ``NIOHTTP2Handler`` is initialized to hold the config until `handlerAdded`. + private enum InboundStreamMultiplexerState { + case uninitializedLegacy + case uninitializedInline(StreamConfiguration, StreamInitializer) + case initialized(InboundStreamMultiplexer) + case deinitialized + + internal var multiplexer: InboundStreamMultiplexer? { + switch self { + case .initialized(let inboundStreamMultiplexer): + return inboundStreamMultiplexer + case .uninitializedLegacy, .uninitializedInline, .deinitialized: + return nil + } + } + + mutating func initialize(context: ChannelHandlerContext, http2Handler: NIOHTTP2Handler, mode: NIOHTTP2Handler.ParserMode) { + switch self { + case .deinitialized: + preconditionFailure("This multiplexer has been de-initialized without being reconfigured with a new context.") + case .uninitializedLegacy: + self = .initialized(.legacy(LegacyInboundStreamMultiplexer(context: context))) + + case .uninitializedInline(let streamConfiguration, let inboundStreamInitializer): + self = .initialized(.inline( + InlineStreamMultiplexer( + context: context, + outboundView: .init(http2Handler: http2Handler), + mode: mode, + inboundStreamStateInitializer: .excludesStreamID(inboundStreamInitializer), + targetWindowSize: max(0, min(streamConfiguration.targetWindowSize, Int(Int32.max))), + streamChannelOutboundBytesHighWatermark: streamConfiguration.outboundBufferSizeHighWatermark, + streamChannelOutboundBytesLowWatermark: streamConfiguration.outboundBufferSizeLowWatermark, + streamDelegate: nil + ) + )) + + case .initialized: + break //no-op + } + } + } /// The mode for this parser to operate in: client or server. public enum ParserMode { @@ -112,7 +165,7 @@ public final class NIOHTTP2Handler: ChannelDuplexHandler { } /// Whether a given operation has validation enabled or not. - public enum ValidationState { + public enum ValidationState: Sendable { /// Validation is enabled case enabled @@ -132,6 +185,7 @@ public final class NIOHTTP2Handler: ChannelDuplexHandler { headerBlockValidation: ValidationState = .enabled, contentLengthValidation: ValidationState = .enabled) { self.init(mode: mode, + eventLoop: nil, initialSettings: initialSettings, headerBlockValidation: headerBlockValidation, contentLengthValidation: contentLengthValidation, @@ -151,18 +205,37 @@ public final class NIOHTTP2Handler: ChannelDuplexHandler { /// - maximumBufferedControlFrames: Controls the maximum buffer size of buffered outbound control frames. If we are unable to send control frames as /// fast as we produce them we risk building up an unbounded buffer and exhausting our memory. To protect against this DoS vector, we put an /// upper limit on the depth of this queue. Defaults to 10,000. - public init(mode: ParserMode, - initialSettings: HTTP2Settings = nioDefaultSettings, - headerBlockValidation: ValidationState = .enabled, - contentLengthValidation: ValidationState = .enabled, - maximumSequentialEmptyDataFrames: Int = 1, - maximumBufferedControlFrames: Int = 10000) { + public convenience init(mode: ParserMode, + initialSettings: HTTP2Settings = nioDefaultSettings, + headerBlockValidation: ValidationState = .enabled, + contentLengthValidation: ValidationState = .enabled, + maximumSequentialEmptyDataFrames: Int = 1, + maximumBufferedControlFrames: Int = 10000) { + self.init(mode: mode, + eventLoop: nil, + initialSettings: initialSettings, + headerBlockValidation: headerBlockValidation, + contentLengthValidation: contentLengthValidation, + maximumSequentialEmptyDataFrames: maximumSequentialEmptyDataFrames, + maximumBufferedControlFrames: maximumBufferedControlFrames) + + } + + private init(mode: ParserMode, + eventLoop: EventLoop?, + initialSettings: HTTP2Settings, + headerBlockValidation: ValidationState, + contentLengthValidation: ValidationState, + maximumSequentialEmptyDataFrames: Int, + maximumBufferedControlFrames: Int) { + self.eventLoop = eventLoop self.stateMachine = HTTP2ConnectionStateMachine(role: .init(mode), headerBlockValidation: .init(headerBlockValidation), contentLengthValidation: .init(contentLengthValidation)) self.mode = mode self.initialSettings = initialSettings self.outboundBuffer = CompoundOutboundBuffer(mode: mode, initialMaxOutboundStreams: 100, maxBufferedControlFrames: maximumBufferedControlFrames) self.denialOfServiceValidator = DOSHeuristics(maximumSequentialEmptyDataFrames: maximumSequentialEmptyDataFrames) self.tolerateImpossibleStateTransitionsInDebugMode = false + self.inboundStreamMultiplexerState = .uninitializedLegacy } /// Constructs a ``NIOHTTP2Handler``. @@ -188,17 +261,19 @@ public final class NIOHTTP2Handler: ChannelDuplexHandler { tolerateImpossibleStateTransitionsInDebugMode: Bool = false) { self.stateMachine = HTTP2ConnectionStateMachine(role: .init(mode), headerBlockValidation: .init(headerBlockValidation), contentLengthValidation: .init(contentLengthValidation)) self.mode = mode + self.eventLoop = nil self.initialSettings = initialSettings self.outboundBuffer = CompoundOutboundBuffer(mode: mode, initialMaxOutboundStreams: 100, maxBufferedControlFrames: maximumBufferedControlFrames) self.denialOfServiceValidator = DOSHeuristics(maximumSequentialEmptyDataFrames: maximumSequentialEmptyDataFrames) self.tolerateImpossibleStateTransitionsInDebugMode = tolerateImpossibleStateTransitionsInDebugMode + self.inboundStreamMultiplexerState = .uninitializedLegacy } public func handlerAdded(context: ChannelHandlerContext) { self.frameDecoder = HTTP2FrameDecoder(allocator: context.channel.allocator, expectClientMagic: self.mode == .server) self.frameEncoder = HTTP2FrameEncoder(allocator: context.channel.allocator) self.writeBuffer = context.channel.allocator.buffer(capacity: 128) - self.inboundStreamMultiplexer = .legacy(LegacyInboundStreamMultiplexer(context: context)) + self.inboundStreamMultiplexerState.initialize(context: context, http2Handler: self, mode: self.mode) if context.channel.isActive { // We jump immediately to activated here, as channelActive has probably already passed. @@ -213,7 +288,7 @@ public final class NIOHTTP2Handler: ChannelDuplexHandler { public func handlerRemoved(context: ChannelHandlerContext) { // Any frames we're buffering need to be dropped. self.outboundBuffer.invalidateBuffer() - self.inboundStreamMultiplexer = nil + self.inboundStreamMultiplexerState = .deinitialized } public func channelActive(context: ChannelHandlerContext) { @@ -251,6 +326,7 @@ public final class NIOHTTP2Handler: ChannelDuplexHandler { } self.writeAndFlushPreamble(context: context) + self.inboundStreamMultiplexer?.channelActiveReceived() // Ok, we progressed. Now we check our state again. switch self.activationState { @@ -282,6 +358,7 @@ public final class NIOHTTP2Handler: ChannelDuplexHandler { // This is the easy one. We were active, now we aren't. self.activationState = .inactive self.channelClosed = true + self.inboundStreamMultiplexer?.channelInactiveReceived() context.fireChannelInactive() case .activating: // Huh, we got channelInactive during activation. We need to maintain @@ -295,7 +372,6 @@ public final class NIOHTTP2Handler: ChannelDuplexHandler { // This is weird. This can only happen if we see channelInactive twice, which is probably an error. self.impossibleActivationStateTransition(state: self.activationState, activating: false, context: context) } - } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { @@ -313,6 +389,8 @@ public final class NIOHTTP2Handler: ChannelDuplexHandler { public func channelReadComplete(context: ChannelHandlerContext) { self.outboundBuffer.flushReceived() self.unbufferAndFlushAutomaticFrames(context: context) + + self.inboundStreamMultiplexer?.channelReadCompleteReceived() context.fireChannelReadComplete() } @@ -333,6 +411,8 @@ public final class NIOHTTP2Handler: ChannelDuplexHandler { if self.channelWritable { self.unbufferAndFlushAutomaticFrames(context: context) } + + self.inboundStreamMultiplexer?.channelWritabilityChangedReceived() context.fireChannelWritabilityChanged() } } @@ -841,6 +921,7 @@ NIOHTTP2Handler( } } + extension NIOHTTP2Handler { /// Tracks the state of activation of the handler. enum ActivationState { @@ -869,3 +950,116 @@ extension NIOHTTP2Handler { context.close(promise: nil) } } + + +extension NIOHTTP2Handler { + /// Exposes restricted API for use by the multiplexer + internal struct OutboundView { + private let http2Handler: NIOHTTP2Handler + + fileprivate init(http2Handler: NIOHTTP2Handler) { + self.http2Handler = http2Handler + } + + func flush(context: ChannelHandlerContext) { + self.http2Handler.flush(context: context) + } + + func write(context: ChannelHandlerContext, frame: HTTP2Frame, promise: EventLoopPromise?) { + self.http2Handler.writeBufferedFrame(context: context, frame: frame, promise: promise) + } + } +} + + +extension NIOHTTP2Handler { +#if swift(>=5.7) + /// The type of all `inboundStreamInitializer` callbacks. + public typealias StreamInitializer = @Sendable (Channel) -> EventLoopFuture +#else + /// The type of all `inboundStreamInitializer` callbacks. + public typealias StreamInitializer = (Channel) -> EventLoopFuture +#endif + + /// Creates a new ``NIOHTTP2Handler`` with a local multiplexer. (i.e. using + /// ``StreamMultiplexer``.) + /// + /// Frames on the root stream will continue to be passed down the main channel, whereas those intended for + /// other streams will be forwarded to the appropriate child channel. + /// + /// To create streams using the local multiplexer, first obtain it via the computed property (`multiplexer`) + /// and then invoke one of the `multiplexer.createStreamChannel` methods. If possible the multiplexer should be + /// stored and used across multiple invocations because obtaining it requires synchronizing on the event loop. + /// + /// The optional `streamDelegate` will be notified of stream creation and + /// close events. + public convenience init( + mode: ParserMode, + eventLoop: EventLoop, + connectionConfiguration: ConnectionConfiguration = .init(), + streamConfiguration: StreamConfiguration = .init(), + streamDelegate: NIOHTTP2StreamDelegate? = nil, + inboundStreamInitializer: @escaping StreamInitializer + ) { + self.init(mode: mode, + eventLoop: eventLoop, + initialSettings: connectionConfiguration.initialSettings, + headerBlockValidation: connectionConfiguration.headerBlockValidation, + contentLengthValidation: connectionConfiguration.contentLengthValidation, + maximumSequentialEmptyDataFrames: connectionConfiguration.maximumSequentialEmptyDataFrames, + maximumBufferedControlFrames: connectionConfiguration.maximumBufferedControlFrames + ) + self.inboundStreamMultiplexerState = .uninitializedInline(streamConfiguration, inboundStreamInitializer) + } + + /// Connection-level configuration. + public struct ConnectionConfiguration: Hashable, Sendable { + public var initialSettings: HTTP2Settings = nioDefaultSettings + public var headerBlockValidation: ValidationState = .enabled + public var contentLengthValidation: ValidationState = .enabled + public var maximumSequentialEmptyDataFrames: Int = 1 + public var maximumBufferedControlFrames: Int = 10000 + public init() {} + } + + /// Stream-level configuration. + public struct StreamConfiguration: Hashable, Sendable { + public var targetWindowSize: Int = 65535 + public var outboundBufferSizeHighWatermark: Int = 8196 + public var outboundBufferSizeLowWatermark: Int = 4092 + public init() {} + } + + /// 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, + /// i.e. it was initialized with an `inboundStreamInitializer`. + public var multiplexer: EventLoopFuture { + // We need to return a future here so that we can synchronize access on the underlying `self.inboundStreamMultiplexer` + if self.eventLoop!.inEventLoop { + return self.eventLoop!.makeCompletedFuture { + return try self.syncMultiplexer() + } + } else { + return self.eventLoop!.submit { + return try self.syncMultiplexer() + } + } + } + + /// Synchronously return a ``StreamMultiplexer`` which can be used to create new outbound HTTP/2 streams. + /// + /// > Note: This is only safe to call if both: + /// > - The ``NIOHTTP2Handler`` uses a local multiplexer, i.e. it was initialized with an `inboundStreamInitializer`. + /// > - The caller is already on the correct event loop. + public func syncMultiplexer() throws -> StreamMultiplexer { + self.eventLoop!.preconditionInEventLoop() + + switch self.inboundStreamMultiplexer { + case let .some(.inline(multiplexer)): + return StreamMultiplexer(multiplexer) + case .some(.legacy), .none: + throw NIOHTTP2Errors.missingMultiplexer() + } + } +} diff --git a/Sources/NIOHTTP2/HTTP2CommonInboundStreamMultiplexer.swift b/Sources/NIOHTTP2/HTTP2CommonInboundStreamMultiplexer.swift new file mode 100644 index 0000000..32e4875 --- /dev/null +++ b/Sources/NIOHTTP2/HTTP2CommonInboundStreamMultiplexer.swift @@ -0,0 +1,301 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2023 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import NIOCore + +/// Represents the common multiplexing machinery used by both legacy ``HTTP2StreamMultiplexer`` and new ``InlineStreamMultiplexer`` inbound stream multiplexing. +internal class HTTP2CommonInboundStreamMultiplexer { + private let channel: Channel + + // NOTE: All state below should only be modified from the `EventLoop` of the supplied `Channel` + + // Streams which have a stream ID. + private var streams: [HTTP2StreamID: MultiplexerAbstractChannel] = [:] + // Streams which don't yet have a stream ID assigned to them. + private var pendingStreams: [ObjectIdentifier: MultiplexerAbstractChannel] = [:] + private var didReadChannels: StreamChannelList = StreamChannelList() + private var nextOutboundStreamID: HTTP2StreamID + private let inboundStreamStateInitializer: MultiplexerAbstractChannel.InboundStreamStateInitializer + + private var connectionFlowControlManager: InboundWindowManager + + private let mode: NIOHTTP2Handler.ParserMode + private let targetWindowSize: Int + private let streamChannelOutboundBytesHighWatermark: Int + private let streamChannelOutboundBytesLowWatermark: Int + + private var isReading = false + private var flushPending = false + + init(mode: NIOHTTP2Handler.ParserMode, channel: Channel, inboundStreamStateInitializer: MultiplexerAbstractChannel.InboundStreamStateInitializer, targetWindowSize: Int, streamChannelOutboundBytesHighWatermark: Int, streamChannelOutboundBytesLowWatermark: Int) { + self.channel = channel + self.inboundStreamStateInitializer = inboundStreamStateInitializer + self.targetWindowSize = targetWindowSize + self.connectionFlowControlManager = InboundWindowManager(targetSize: Int32(targetWindowSize)) + self.streamChannelOutboundBytesHighWatermark = streamChannelOutboundBytesHighWatermark + self.streamChannelOutboundBytesLowWatermark = streamChannelOutboundBytesLowWatermark + self.mode = mode + switch mode { + case .client: + self.nextOutboundStreamID = 1 + case .server: + self.nextOutboundStreamID = 2 + } + } +} + +// MARK:- inbound multiplexer functions +// note this is intentionally not bound to `HTTP2InboundStreamMultiplexer` to allow for freedom in modifying the shared driver function signatures +extension HTTP2CommonInboundStreamMultiplexer { + func receivedFrame(_ frame: HTTP2Frame, context: ChannelHandlerContext, multiplexer: HTTP2StreamChannel.OutboundStreamMultiplexer) { + self.channel.eventLoop.preconditionInEventLoop() + + self.isReading = true + let streamID = frame.streamID + if streamID == .rootStream { + // For stream 0 we forward all frames on to the main channel. + context.fireChannelRead(NIOAny(frame)) + return + } + + if case .priority = frame.payload { + // Priority frames are special cases, and are always forwarded to the parent stream. + context.fireChannelRead(NIOAny(frame)) + return + } + + if let channel = self.streams[streamID] { + channel.receiveInboundFrame(frame) + if !channel.inList { + self.didReadChannels.append(channel) + } + } else if case .headers = frame.payload { + let channel = MultiplexerAbstractChannel( + allocator: self.channel.allocator, + parent: self.channel, + multiplexer: multiplexer, + streamID: streamID, + targetWindowSize: Int32(self.targetWindowSize), + outboundBytesHighWatermark: self.streamChannelOutboundBytesHighWatermark, + outboundBytesLowWatermark: self.streamChannelOutboundBytesLowWatermark, + inboundStreamStateInitializer: self.inboundStreamStateInitializer + ) + + self.streams[streamID] = channel + channel.configureInboundStream(initializer: self.inboundStreamStateInitializer) + channel.receiveInboundFrame(frame) + + if !channel.inList { + self.didReadChannels.append(channel) + } + } else { + // This frame is for a stream we know nothing about. We can't do much about it, so we + // are going to fire an error and drop the frame. + let error = NIOHTTP2Errors.noSuchStream(streamID: streamID) + context.fireErrorCaught(error) + } + } + + func streamError(context: ChannelHandlerContext, _ streamError: NIOHTTP2Errors.StreamError) { + self.channel.eventLoop.preconditionInEventLoop() + self.streams[streamError.streamID]?.receiveStreamError(streamError) + context.fireErrorCaught(streamError.baseError) + } + + func streamCreated(event: NIOHTTP2StreamCreatedEvent) { + self.channel.eventLoop.preconditionInEventLoop() + self.streams[event.streamID]?.networkActivationReceived() + } + + func streamClosed(event: StreamClosedEvent) { + self.channel.eventLoop.preconditionInEventLoop() + self.streams[event.streamID]?.receiveStreamClosed(event.reason) + } + + func newConnectionWindowSize(_ newSize: Int) -> Int? { + self.channel.eventLoop.preconditionInEventLoop() + return self.connectionFlowControlManager.newWindowSize(newSize) + } + + func childStreamWindowUpdated(event: NIOHTTP2WindowUpdatedEvent) { + self.channel.eventLoop.preconditionInEventLoop() + precondition(event.streamID != .rootStream, "not to be called on the root stream") + + if let windowSize = event.inboundWindowSize { + self.streams[event.streamID]?.receiveWindowUpdatedEvent(windowSize) + } + } + + func initialStreamWindowChanged(event: NIOHTTP2BulkStreamWindowChangeEvent) { + // Here we need to pull the channels out so we aren't holding the streams dict mutably. This is because it + // will trigger an overlapping access violation if we do. + let channels = self.streams.values + for channel in channels { + channel.initialWindowSizeChanged(delta: event.delta) + } + } +} + +extension HTTP2CommonInboundStreamMultiplexer { + internal func propagateChannelActive(context: ChannelHandlerContext) { + // We double-check the channel activity here, because it's possible action taken during + // the activation of one of the child channels will cause the parent to close! + for channel in self.streams.values { + if context.channel.isActive { + channel.performActivation() + } + } + for channel in self.pendingStreams.values { + if context.channel.isActive { + channel.performActivation() + } + } + } + + internal func propagateChannelInactive() { + for channel in self.streams.values { + channel.receiveStreamClosed(nil) + } + for channel in self.pendingStreams.values { + channel.receiveStreamClosed(nil) + } + } + + internal func propagateChannelWritabilityChanged(context: ChannelHandlerContext) { + for channel in self.streams.values { + channel.parentChannelWritabilityChanged(newValue: context.channel.isWritable) + } + for channel in self.pendingStreams.values { + channel.parentChannelWritabilityChanged(newValue: context.channel.isWritable) + } + } + + enum ReadFlushNeeded { + case flushNow + case noop + } + + /// returns `.flushPending` if there was a flush pending which may now be performed + internal func propagateReadComplete() -> ReadFlushNeeded { + // Call channelReadComplete on the children until this has been propagated enough. + while let channel = self.didReadChannels.removeFirst() { + channel.receiveParentChannelReadComplete() + } + + // stash the state before clearing + let readFlushNeeded: ReadFlushNeeded = self.flushPending ? .flushNow : .noop + + self.isReading = false + self.flushPending = false + + return readFlushNeeded + } + + enum ReadFlushCoalescingState { + case waitForReadsToComplete + case proceed + } + + /// Communicates the intention to flush + internal func flushDesired() -> ReadFlushCoalescingState { + if self.isReading { + self.flushPending = true + return .waitForReadsToComplete + } + return .proceed + } + + internal func clearDidReadChannels() { + self.didReadChannels.removeAll() + } +} + +// MARK:- Child to parent calls +extension HTTP2CommonInboundStreamMultiplexer { + internal func childChannelClosed(streamID: HTTP2StreamID) { + self.streams.removeValue(forKey: streamID) + } + + internal func childChannelClosed(channelID: ObjectIdentifier) { + self.pendingStreams.removeValue(forKey: channelID) + } + + /// Requests a ``HTTP2StreamID`` for the given `Channel`. + /// + /// - Precondition: The `channel` must not already have a `streamID`. + internal func requestStreamID(forChannel channel: Channel) -> HTTP2StreamID { + let channelID = ObjectIdentifier(channel) + + // This unwrap shouldn't fail: the multiplexer owns the stream and the stream only requests + // a streamID once. + guard let abstractChannel = self.pendingStreams.removeValue(forKey: channelID) else { + preconditionFailure("No pending streams have channelID \(channelID)") + } + assert(abstractChannel.channelID == channelID) + + let streamID = self.nextStreamID() + self.streams[streamID] = abstractChannel + return streamID + } + + private func nextStreamID() -> HTTP2StreamID { + let streamID = self.nextOutboundStreamID + self.nextOutboundStreamID = HTTP2StreamID(Int32(streamID) + 2) + return streamID + } +} + +extension HTTP2CommonInboundStreamMultiplexer { + internal func createStreamChannel(multiplexer: HTTP2StreamChannel.OutboundStreamMultiplexer, promise: EventLoopPromise?, _ streamStateInitializer: @escaping (Channel) -> EventLoopFuture) { + self.channel.eventLoop.execute { + let channel = MultiplexerAbstractChannel( + allocator: self.channel.allocator, + parent: self.channel, + multiplexer: multiplexer, + streamID: nil, + targetWindowSize: Int32(self.targetWindowSize), + outboundBytesHighWatermark: self.streamChannelOutboundBytesHighWatermark, + outboundBytesLowWatermark: self.streamChannelOutboundBytesLowWatermark, + inboundStreamStateInitializer: .excludesStreamID(nil) + ) + self.pendingStreams[channel.channelID] = channel + channel.configure(initializer: streamStateInitializer, userPromise: promise) + } + } + + internal func createStreamChannel(multiplexer: HTTP2StreamChannel.OutboundStreamMultiplexer, _ streamStateInitializer: @escaping (Channel) -> EventLoopFuture) -> EventLoopFuture { + let promise = self.channel.eventLoop.makePromise(of: Channel.self) + self.createStreamChannel(multiplexer: multiplexer, promise: promise, streamStateInitializer) + return promise.futureResult + } + + @available(*, deprecated, message: "The signature of 'streamStateInitializer' has changed to '(Channel) -> EventLoopFuture'") + internal func createStreamChannel(multiplexer: HTTP2StreamChannel.OutboundStreamMultiplexer, promise: EventLoopPromise?, _ streamStateInitializer: @escaping (Channel, HTTP2StreamID) -> EventLoopFuture) { + self.channel.eventLoop.execute { + let streamID = self.nextStreamID() + let channel = MultiplexerAbstractChannel( + allocator: self.channel.allocator, + parent: self.channel, + multiplexer: multiplexer, + streamID: streamID, + targetWindowSize: Int32(self.targetWindowSize), + outboundBytesHighWatermark: self.streamChannelOutboundBytesHighWatermark, + outboundBytesLowWatermark: self.streamChannelOutboundBytesLowWatermark, + inboundStreamStateInitializer: .includesStreamID(nil) + ) + self.streams[streamID] = channel + channel.configure(initializer: streamStateInitializer, userPromise: promise) + } + } +} diff --git a/Sources/NIOHTTP2/HTTP2Error.swift b/Sources/NIOHTTP2/HTTP2Error.swift index c6081ea..4d3bcea 100644 --- a/Sources/NIOHTTP2/HTTP2Error.swift +++ b/Sources/NIOHTTP2/HTTP2Error.swift @@ -284,6 +284,11 @@ public enum NIOHTTP2Errors { return NoStreamIDAvailable(file: file, line: line) } + /// Creates a ``MissingMultiplexer`` error with appropriate source context. + public static func missingMultiplexer(file: String = #fileID, line: UInt = #line) -> MissingMultiplexer { + return MissingMultiplexer(file: file, line: line) + } + /// Creates a ``StreamError`` error with appropriate source context. /// /// - parameters: @@ -1641,6 +1646,26 @@ public enum NIOHTTP2Errors { } } } + + /// The ``HTTP2ChannelHandler`` does not have a multiplexer but one has been accessed. + public struct MissingMultiplexer: NIOHTTP2Error { + private let file: String + private let line: UInt + + /// The location where the error was thrown. + public var location: String { + return _location(file: self.file, line: self.line) + } + + fileprivate init(file: String, line: UInt) { + self.file = file + self.line = line + } + + public static func ==(lhs: Self, rhs: Self) -> Bool { + return true + } + } } diff --git a/Sources/NIOHTTP2/HTTP2Settings.swift b/Sources/NIOHTTP2/HTTP2Settings.swift index a945a6c..91ba29d 100644 --- a/Sources/NIOHTTP2/HTTP2Settings.swift +++ b/Sources/NIOHTTP2/HTTP2Settings.swift @@ -104,3 +104,10 @@ extension HTTP2Setting: Equatable { return lhs.parameter == rhs.parameter && lhs._value == rhs._value } } + +extension HTTP2Setting: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(self.parameter) + hasher.combine(self._value) + } +} diff --git a/Sources/NIOHTTP2/HTTP2StreamChannel+OutboundStreamMultiplexer.swift b/Sources/NIOHTTP2/HTTP2StreamChannel+OutboundStreamMultiplexer.swift index d8996c6..8e9bb2f 100644 --- a/Sources/NIOHTTP2/HTTP2StreamChannel+OutboundStreamMultiplexer.swift +++ b/Sources/NIOHTTP2/HTTP2StreamChannel+OutboundStreamMultiplexer.swift @@ -43,50 +43,50 @@ extension HTTP2StreamChannel { /// We use an enum for this purpose since we can't use a generic (for API compatibility reasons) and it allows us to avoid the cost of using an existential. internal enum OutboundStreamMultiplexer: HTTP2OutboundStreamMultiplexer { case legacy(LegacyOutboundStreamMultiplexer) - case new + case inline(InlineStreamMultiplexer) func writeFrame(_ frame: HTTP2Frame, promise: NIOCore.EventLoopPromise?) { switch self { - case .legacy(let multiplexer): - multiplexer.writeFrame(frame, promise: promise) - case .new: - fatalError("Not yet implemented.") + case .legacy(let legacyOutboundMultiplexer): + legacyOutboundMultiplexer.writeFrame(frame, promise: promise) + case .inline(let inlineStreamMultiplexer): + inlineStreamMultiplexer.writeFrame(frame, promise: promise) } } func flushStream(_ id: HTTP2StreamID) { switch self { - case .legacy(let multiplexer): - multiplexer.flushStream(id) - case .new: - fatalError("Not yet implemented.") + case .legacy(let legacyOutboundMultiplexer): + legacyOutboundMultiplexer.flushStream(id) + case .inline(let inlineStreamMultiplexer): + inlineStreamMultiplexer.flushStream(id) } } func requestStreamID(forChannel: NIOCore.Channel) -> HTTP2StreamID { switch self { - case .legacy(let multiplexer): - return multiplexer.requestStreamID(forChannel: forChannel) - case .new: - fatalError("Not yet implemented") + case .legacy(let legacyOutboundMultiplexer): + return legacyOutboundMultiplexer.requestStreamID(forChannel: forChannel) + case .inline(let inlineStreamMultiplexer): + return inlineStreamMultiplexer.requestStreamID(forChannel: forChannel) } } func streamClosed(channelID: ObjectIdentifier) { switch self { - case .legacy(let multiplexer): - multiplexer.streamClosed(channelID: channelID) - case .new: - fatalError("Not yet implemented.") + case .legacy(let legacyOutboundMultiplexer): + legacyOutboundMultiplexer.streamClosed(channelID: channelID) + case .inline(let inlineStreamMultiplexer): + inlineStreamMultiplexer.streamClosed(channelID: channelID) } } func streamClosed(id: HTTP2StreamID) { switch self { - case .legacy(let multiplexer): - multiplexer.streamClosed(id: id) - case .new: - fatalError("Not yet implemented.") + case .legacy(let legacyOutboundMultiplexer): + legacyOutboundMultiplexer.streamClosed(id: id) + case .inline(let inlineStreamMultiplexer): + inlineStreamMultiplexer.streamClosed(id: id) } } } diff --git a/Sources/NIOHTTP2/HTTP2StreamChannel.swift b/Sources/NIOHTTP2/HTTP2StreamChannel.swift index 9b88221..c85122c 100644 --- a/Sources/NIOHTTP2/HTTP2StreamChannel.swift +++ b/Sources/NIOHTTP2/HTTP2StreamChannel.swift @@ -151,7 +151,7 @@ final class HTTP2StreamChannel: Channel, ChannelCore { internal init(allocator: ByteBufferAllocator, parent: Channel, - multiplexer: HTTP2StreamMultiplexer, + multiplexer: OutboundStreamMultiplexer, streamID: HTTP2StreamID?, targetWindowSize: Int32, outboundBytesHighWatermark: Int, @@ -164,7 +164,7 @@ final class HTTP2StreamChannel: Channel, ChannelCore { self.parent = parent self.eventLoop = parent.eventLoop self.streamID = streamID - self.multiplexer = .legacy(LegacyOutboundStreamMultiplexer(multiplexer: multiplexer)) + self.multiplexer = multiplexer self.windowManager = InboundWindowManager(targetSize: Int32(targetWindowSize)) self._isActiveAtomic = .init(false) self._isWritable = .init(true) diff --git a/Sources/NIOHTTP2/HTTP2StreamDelegate.swift b/Sources/NIOHTTP2/HTTP2StreamDelegate.swift new file mode 100644 index 0000000..4125449 --- /dev/null +++ b/Sources/NIOHTTP2/HTTP2StreamDelegate.swift @@ -0,0 +1,26 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2023 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import NIOCore + +/// A delegate which can be used with the ``NIOHTTP2Handler`` and its multiplexer. +/// +/// Delegates are called when the multiplexer creates or closes HTTP/2 streams. +public protocol NIOHTTP2StreamDelegate { + /// A new HTTP/2 stream was created with the given ID. + func streamCreated(_ id: HTTP2StreamID, channel: Channel) + + /// An HTTP/2 stream with the given ID was closed. + func streamClosed(_ id: HTTP2StreamID, channel: Channel) +} diff --git a/Sources/NIOHTTP2/HTTP2StreamMultiplexer.swift b/Sources/NIOHTTP2/HTTP2StreamMultiplexer.swift index 716673c..744f00c 100644 --- a/Sources/NIOHTTP2/HTTP2StreamMultiplexer.swift +++ b/Sources/NIOHTTP2/HTTP2StreamMultiplexer.swift @@ -28,20 +28,10 @@ public final class HTTP2StreamMultiplexer: ChannelInboundHandler, ChannelOutboun public typealias OutboundIn = HTTP2Frame public typealias OutboundOut = HTTP2Frame - // Streams which have a stream ID. - private var streams: [HTTP2StreamID: MultiplexerAbstractChannel] = [:] - // Streams which don't yet have a stream ID assigned to them. - private var pendingStreams: [ObjectIdentifier: MultiplexerAbstractChannel] = [:] - private let inboundStreamStateInitializer: MultiplexerAbstractChannel.InboundStreamStateInitializer private let channel: Channel private var context: ChannelHandlerContext! - private var nextOutboundStreamID: HTTP2StreamID - private var connectionFlowControlManager: InboundWindowManager - private var flushState: FlushState = .notReading - private var didReadChannels: StreamChannelList = StreamChannelList() - private let streamChannelOutboundBytesHighWatermark: Int - private let streamChannelOutboundBytesLowWatermark: Int - private let targetWindowSize: Int + + private let commonStreamMultiplexer: HTTP2CommonInboundStreamMultiplexer public func handlerAdded(context: ChannelHandlerContext) { // We now need to check that we're on the same event loop as the one we were originally given. @@ -52,81 +42,31 @@ public final class HTTP2StreamMultiplexer: ChannelInboundHandler, ChannelOutboun public func handlerRemoved(context: ChannelHandlerContext) { self.context = nil - self.didReadChannels.removeAll() + self.commonStreamMultiplexer.clearDidReadChannels() } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { let frame = self.unwrapInboundIn(data) - let streamID = frame.streamID - - self.flushState.startReading() - - guard streamID != .rootStream else { - // For stream 0 we forward all frames on to the main channel. - context.fireChannelRead(data) - return - } - - if case .priority = frame.payload { - // Priority frames are special cases, and are always forwarded to the parent stream. - context.fireChannelRead(data) - return - } - - if let channel = self.streams[streamID] { - channel.receiveInboundFrame(frame) - if !channel.inList { - self.didReadChannels.append(channel) - } - } else if case .headers = frame.payload { - let channel = MultiplexerAbstractChannel( - allocator: self.channel.allocator, - parent: self.channel, - multiplexer: self, - streamID: streamID, - targetWindowSize: Int32(self.targetWindowSize), - outboundBytesHighWatermark: self.streamChannelOutboundBytesHighWatermark, - outboundBytesLowWatermark: self.streamChannelOutboundBytesLowWatermark, - inboundStreamStateInitializer: self.inboundStreamStateInitializer - ) - - self.streams[streamID] = channel - channel.configureInboundStream(initializer: self.inboundStreamStateInitializer) - channel.receiveInboundFrame(frame) - - if !channel.inList { - self.didReadChannels.append(channel) - } - } else { - // This frame is for a stream we know nothing about. We can't do much about it, so we - // are going to fire an error and drop the frame. - let error = NIOHTTP2Errors.noSuchStream(streamID: streamID) - context.fireErrorCaught(error) - } + self.commonStreamMultiplexer.receivedFrame(frame, context: context, multiplexer: .legacy(LegacyOutboundStreamMultiplexer(multiplexer: self))) } public func channelReadComplete(context: ChannelHandlerContext) { - // Call channelReadComplete on the children until this has been propagated enough. - while let channel = self.didReadChannels.removeFirst() { - channel.receiveParentChannelReadComplete() - } - - if case .flushPending = self.flushState { - self.flushState = .notReading + switch self.commonStreamMultiplexer.propagateReadComplete() { + case .flushNow: context.flush() - } else { - self.flushState = .notReading + case .noop: + break } context.fireChannelReadComplete() } public func flush(context: ChannelHandlerContext) { - switch self.flushState { - case .reading, .flushPending: - self.flushState = .flushPending - case .notReading: + switch self.commonStreamMultiplexer.flushDesired() { + case .proceed: context.flush() + case .waitForReadsToComplete: + break // flush will be executed on `channelReadComplete` } } @@ -137,29 +77,13 @@ public final class HTTP2StreamMultiplexer: ChannelInboundHandler, ChannelOutboun public func channelActive(context: ChannelHandlerContext) { // We just got channelActive. Any previously existing channels may be marked active. - self.activateChannels(self.streams.values, context: context) - self.activateChannels(self.pendingStreams.values, context: context) + self.commonStreamMultiplexer.propagateChannelActive(context: context) context.fireChannelActive() } - private func activateChannels(_ channels: Channels, context: ChannelHandlerContext) where Channels.Element == MultiplexerAbstractChannel { - for channel in channels { - // We double-check the channel activity here, because it's possible action taken during - // the activation of one of the child channels will cause the parent to close! - if context.channel.isActive { - channel.performActivation() - } - } - } - public func channelInactive(context: ChannelHandlerContext) { - for channel in self.streams.values { - channel.receiveStreamClosed(nil) - } - for channel in self.pendingStreams.values { - channel.receiveStreamClosed(nil) - } + self.commonStreamMultiplexer.propagateChannelInactive() context.fireChannelInactive() } @@ -167,27 +91,16 @@ public final class HTTP2StreamMultiplexer: ChannelInboundHandler, ChannelOutboun public func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) { switch event { case let evt as StreamClosedEvent: - if let channel = self.streams[evt.streamID] { - channel.receiveStreamClosed(evt.reason) - } + self.commonStreamMultiplexer.streamClosed(event: evt) case let evt as NIOHTTP2WindowUpdatedEvent where evt.streamID == .rootStream: // This force-unwrap is safe: we always have a connection window. self.newConnectionWindowSize(newSize: evt.inboundWindowSize!, context: context) case let evt as NIOHTTP2WindowUpdatedEvent: - if let channel = self.streams[evt.streamID], let windowSize = evt.inboundWindowSize { - channel.receiveWindowUpdatedEvent(windowSize) - } + self.commonStreamMultiplexer.childStreamWindowUpdated(event: evt) case let evt as NIOHTTP2BulkStreamWindowChangeEvent: - // Here we need to pull the channels out so we aren't holding the streams dict mutably. This is because it - // will trigger an overlapping access violation if we do. - let channels = self.streams.values - for channel in channels { - channel.initialWindowSizeChanged(delta: evt.delta) - } + self.commonStreamMultiplexer.initialStreamWindowChanged(event: evt) case let evt as NIOHTTP2StreamCreatedEvent: - if let channel = self.streams[evt.streamID] { - channel.networkActivationReceived() - } + self.commonStreamMultiplexer.streamCreated(event: evt) default: break } @@ -196,27 +109,20 @@ public final class HTTP2StreamMultiplexer: ChannelInboundHandler, ChannelOutboun } public func channelWritabilityChanged(context: ChannelHandlerContext) { - for channel in self.streams.values { - channel.parentChannelWritabilityChanged(newValue: context.channel.isWritable) - } - for channel in self.pendingStreams.values { - channel.parentChannelWritabilityChanged(newValue: context.channel.isWritable) - } + self.commonStreamMultiplexer.propagateChannelWritabilityChanged(context: context) context.fireChannelWritabilityChanged() } public func errorCaught(context: ChannelHandlerContext, error: Error) { - if let streamError = error as? NIOHTTP2Errors.StreamError, - let channel = self.streams[streamError.streamID] { - channel.receiveStreamError(streamError) + if let streamError = error as? NIOHTTP2Errors.StreamError { + self.commonStreamMultiplexer.streamError(context: context, streamError) } - context.fireErrorCaught(error) } private func newConnectionWindowSize(newSize: Int, context: ChannelHandlerContext) { - guard let increment = self.connectionFlowControlManager.newWindowSize(newSize) else { + guard let increment = self.commonStreamMultiplexer.newConnectionWindowSize(newSize) else { return } @@ -315,47 +221,20 @@ public final class HTTP2StreamMultiplexer: ChannelInboundHandler, ChannelOutboun outboundBufferSizeHighWatermark: Int, outboundBufferSizeLowWatermark: Int, inboundStreamStateInitializer: MultiplexerAbstractChannel.InboundStreamStateInitializer) { - self.inboundStreamStateInitializer = inboundStreamStateInitializer self.channel = channel - self.targetWindowSize = max(0, min(targetWindowSize, Int(Int32.max))) - self.connectionFlowControlManager = InboundWindowManager(targetSize: Int32(targetWindowSize)) - self.streamChannelOutboundBytesHighWatermark = outboundBufferSizeHighWatermark - self.streamChannelOutboundBytesLowWatermark = outboundBufferSizeLowWatermark - switch mode { - case .client: - self.nextOutboundStreamID = 1 - case .server: - self.nextOutboundStreamID = 2 - } + self.commonStreamMultiplexer = HTTP2CommonInboundStreamMultiplexer( + mode: mode, + channel: channel, + inboundStreamStateInitializer: inboundStreamStateInitializer, + targetWindowSize: targetWindowSize, + streamChannelOutboundBytesHighWatermark: outboundBufferSizeHighWatermark, + streamChannelOutboundBytesLowWatermark: outboundBufferSizeLowWatermark + ) } } -extension HTTP2StreamMultiplexer { - /// The state of the multiplexer for flush coalescing. - /// - /// The stream multiplexer aims to perform limited flush coalescing on the read side by delaying flushes from the child and - /// parent channels until channelReadComplete is received. To do this we need to track what state we're in. - enum FlushState { - /// No channelReads have been fired since the last channelReadComplete, so we probably aren't reading. Let any - /// flushes through. - case notReading - - /// We've started reading, but don't have any pending flushes. - case reading - - /// We're in the read loop, and have received a flush. - case flushPending - - mutating func startReading() { - if case .notReading = self { - self = .reading - } - } - } -} - extension HTTP2StreamMultiplexer { /// Create a new `Channel` for a new stream initiated by this peer. @@ -371,20 +250,7 @@ extension HTTP2StreamMultiplexer { /// - streamStateInitializer: A callback that will be invoked to allow you to configure the /// `ChannelPipeline` for the newly created channel. public func createStreamChannel(promise: EventLoopPromise?, _ streamStateInitializer: @escaping (Channel) -> EventLoopFuture) { - self.channel.eventLoop.execute { - let channel = MultiplexerAbstractChannel( - allocator: self.channel.allocator, - parent: self.channel, - multiplexer: self, - streamID: nil, - targetWindowSize: Int32(self.targetWindowSize), - outboundBytesHighWatermark: self.streamChannelOutboundBytesHighWatermark, - outboundBytesLowWatermark: self.streamChannelOutboundBytesLowWatermark, - inboundStreamStateInitializer: .excludesStreamID(nil) - ) - self.pendingStreams[channel.channelID] = channel - channel.configure(initializer: streamStateInitializer, userPromise: promise) - } + self.commonStreamMultiplexer.createStreamChannel(multiplexer: .legacy(LegacyOutboundStreamMultiplexer(multiplexer: self)), promise: promise, streamStateInitializer) } /// Create a new `Channel` for a new stream initiated by this peer. @@ -401,27 +267,7 @@ extension HTTP2StreamMultiplexer { /// `ChannelPipeline` for the newly created channel. @available(*, deprecated, message: "The signature of 'streamStateInitializer' has changed to '(Channel) -> EventLoopFuture'") public func createStreamChannel(promise: EventLoopPromise?, _ streamStateInitializer: @escaping (Channel, HTTP2StreamID) -> EventLoopFuture) { - self.channel.eventLoop.execute { - let streamID = self.nextStreamID() - let channel = MultiplexerAbstractChannel( - allocator: self.channel.allocator, - parent: self.channel, - multiplexer: self, - streamID: streamID, - targetWindowSize: Int32(self.targetWindowSize), - outboundBytesHighWatermark: self.streamChannelOutboundBytesHighWatermark, - outboundBytesLowWatermark: self.streamChannelOutboundBytesLowWatermark, - inboundStreamStateInitializer: .includesStreamID(nil) - ) - self.streams[streamID] = channel - channel.configure(initializer: streamStateInitializer, userPromise: promise) - } - } - - private func nextStreamID() -> HTTP2StreamID { - let streamID = self.nextOutboundStreamID - self.nextOutboundStreamID = HTTP2StreamID(Int32(streamID) + 2) - return streamID + self.commonStreamMultiplexer.createStreamChannel(multiplexer: .legacy(LegacyOutboundStreamMultiplexer(multiplexer: self)), promise: promise, streamStateInitializer) } } @@ -429,11 +275,11 @@ extension HTTP2StreamMultiplexer { // MARK:- Child to parent calls extension HTTP2StreamMultiplexer { internal func childChannelClosed(streamID: HTTP2StreamID) { - self.streams.removeValue(forKey: streamID) + self.commonStreamMultiplexer.childChannelClosed(streamID: streamID) } internal func childChannelClosed(channelID: ObjectIdentifier) { - self.pendingStreams.removeValue(forKey: channelID) + self.commonStreamMultiplexer.childChannelClosed(channelID: channelID) } internal func childChannelWrite(_ frame: HTTP2Frame, promise: EventLoopPromise?) { @@ -444,21 +290,10 @@ extension HTTP2StreamMultiplexer { self.flush(context: self.context) } - /// Requests a `HTTP2StreamID` for the given `Channel`. + /// Requests a ``HTTP2StreamID`` for the given `Channel`. /// /// - Precondition: The `channel` must not already have a `streamID`. internal func requestStreamID(forChannel channel: Channel) -> HTTP2StreamID { - let channelID = ObjectIdentifier(channel) - - // This unwrap shouldn't fail: the multiplexer owns the stream and the stream only requests - // a streamID once. - guard let abstractChannel = self.pendingStreams.removeValue(forKey: channelID) else { - preconditionFailure("No pending streams have channelID \(channelID)") - } - assert(abstractChannel.channelID == channelID) - - let streamID = self.nextStreamID() - self.streams[streamID] = abstractChannel - return streamID + self.commonStreamMultiplexer.requestStreamID(forChannel: channel) } } diff --git a/Sources/NIOHTTP2/MultiplexerAbstractChannel.swift b/Sources/NIOHTTP2/MultiplexerAbstractChannel.swift index d6f76b9..7501ebe 100644 --- a/Sources/NIOHTTP2/MultiplexerAbstractChannel.swift +++ b/Sources/NIOHTTP2/MultiplexerAbstractChannel.swift @@ -28,7 +28,7 @@ struct MultiplexerAbstractChannel { init(allocator: ByteBufferAllocator, parent: Channel, - multiplexer: HTTP2StreamMultiplexer, + multiplexer: HTTP2StreamChannel.OutboundStreamMultiplexer, streamID: HTTP2StreamID?, targetWindowSize: Int32, outboundBytesHighWatermark: Int, diff --git a/Tests/LinuxMain.swift b/Tests/LinuxMain.swift index 488d213..f6f7575 100644 --- a/Tests/LinuxMain.swift +++ b/Tests/LinuxMain.swift @@ -48,6 +48,7 @@ class LinuxMainRunner { testCase(HTTP2FrameParserTests.allTests), testCase(HTTP2FramePayloadStreamMultiplexerTests.allTests), testCase(HTTP2FramePayloadToHTTP1CodecTests.allTests), + testCase(HTTP2InlineStreamMultiplexerTests.allTests), testCase(HTTP2StreamMultiplexerTests.allTests), testCase(HTTP2ToHTTP1CodecTests.allTests), testCase(HeaderTableTests.allTests), @@ -57,6 +58,7 @@ class LinuxMainRunner { testCase(OutboundFlowControlBufferTests.allTests), testCase(ReentrancyTests.allTests), testCase(SimpleClientServerFramePayloadStreamTests.allTests), + testCase(SimpleClientServerInlineStreamMultiplexerTests.allTests), testCase(SimpleClientServerTests.allTests), testCase(StreamChannelFlowControllerTests.allTests), testCase(StreamIDTests.allTests), diff --git a/Tests/NIOHTTP2Tests/HTTP2FramePayloadStreamMultiplexerTests.swift b/Tests/NIOHTTP2Tests/HTTP2FramePayloadStreamMultiplexerTests.swift index 55f6a23..7a723ed 100644 --- a/Tests/NIOHTTP2Tests/HTTP2FramePayloadStreamMultiplexerTests.swift +++ b/Tests/NIOHTTP2Tests/HTTP2FramePayloadStreamMultiplexerTests.swift @@ -31,7 +31,7 @@ private extension Channel { private struct MyError: Error { } /// A handler that asserts the frames received match the expected set. -private final class FramePayloadExpecter: ChannelInboundHandler { +internal final class FramePayloadExpecter: ChannelInboundHandler { typealias InboundIn = HTTP2Frame.FramePayload typealias OutboundOut = HTTP2Frame.FramePayload @@ -1371,7 +1371,6 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { // We're going to send in 10 request frames. let requestHeaders = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) XCTAssertEqual(flushCounter.flushCount, 0) - let framesToSend = stride(from: 1, through: 19, by: 2).map { HTTP2Frame(streamID: HTTP2StreamID($0), payload: .headers(.init(headers: requestHeaders, endStream: true))) } for frame in framesToSend { self.channel.pipeline.fireChannelRead(NIOAny(frame)) diff --git a/Tests/NIOHTTP2Tests/HTTP2InlineStreamMultiplexerTests+XCTest.swift b/Tests/NIOHTTP2Tests/HTTP2InlineStreamMultiplexerTests+XCTest.swift new file mode 100644 index 0000000..a751585 --- /dev/null +++ b/Tests/NIOHTTP2Tests/HTTP2InlineStreamMultiplexerTests+XCTest.swift @@ -0,0 +1,78 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// +// +// HTTP2InlineStreamMultiplexerTests+XCTest.swift +// +import XCTest + +/// +/// NOTE: This file was generated by generate_linux_tests.rb +/// +/// Do NOT edit this file directly as it will be regenerated automatically when needed. +/// + +extension HTTP2InlineStreamMultiplexerTests { + + @available(*, deprecated, message: "not actually deprecated. Just deprecated to allow deprecated tests (which test deprecated functionality) without warnings") + static var allTests : [(String, (HTTP2InlineStreamMultiplexerTests) -> () throws -> Void)] { + return [ + ("testMultiplexerIgnoresFramesOnStream0", testMultiplexerIgnoresFramesOnStream0), + ("testHeadersFramesCreateNewChannels", testHeadersFramesCreateNewChannels), + ("testChannelsCloseThemselvesWhenToldTo", testChannelsCloseThemselvesWhenToldTo), + ("testChannelsCloseAfterResetStreamFrameFirstThenEvent", testChannelsCloseAfterResetStreamFrameFirstThenEvent), + ("testChannelsCloseAfterGoawayFrameFirstThenEvent", testChannelsCloseAfterGoawayFrameFirstThenEvent), + ("testClosingIdleChannels", testClosingIdleChannels), + ("testClosingActiveChannels", testClosingActiveChannels), + ("testClosePromiseIsSatisfied", testClosePromiseIsSatisfied), + ("testMultipleClosePromisesAreSatisfied", testMultipleClosePromisesAreSatisfied), + ("testClosePromiseFailsWithError", testClosePromiseFailsWithError), + ("testFramesAreNotDeliveredUntilStreamIsSetUp", testFramesAreNotDeliveredUntilStreamIsSetUp), + ("testFramesAreNotDeliveredIfSetUpFails", testFramesAreNotDeliveredIfSetUpFails), + ("testFlushingOneChannelDoesntFlushThemAll", testFlushingOneChannelDoesntFlushThemAll), + ("testUnflushedWritesFailOnError", testUnflushedWritesFailOnError), + ("testWritesFailOnClosedStreamChannels", testWritesFailOnClosedStreamChannels), + ("testReadPullsInAllFrames", testReadPullsInAllFrames), + ("testReadIsPerChannel", testReadIsPerChannel), + ("testReadWillCauseAutomaticFrameDelivery", testReadWillCauseAutomaticFrameDelivery), + ("testReadWithNoPendingDataCausesReadOnParentChannel", testReadWithNoPendingDataCausesReadOnParentChannel), + ("testHandlersAreRemovedOnClosure", testHandlersAreRemovedOnClosure), + ("testHandlersAreRemovedOnClosureWithError", testHandlersAreRemovedOnClosureWithError), + ("testCreatingOutboundChannelClient", testCreatingOutboundChannelClient), + ("testWritesOnCreatedChannelAreDelayed", testWritesOnCreatedChannelAreDelayed), + ("testWritesAreCancelledOnFailingInitializer", testWritesAreCancelledOnFailingInitializer), + ("testFailingInitializerDoesNotWrite", testFailingInitializerDoesNotWrite), + ("testCreatedChildChannelDoesNotActivateEarly", testCreatedChildChannelDoesNotActivateEarly), + ("testCreatedChildChannelActivatesIfParentIsActive", testCreatedChildChannelActivatesIfParentIsActive), + ("testInitiatedChildChannelActivates", testInitiatedChildChannelActivates), + ("testMultiplexerIgnoresPriorityFrames", testMultiplexerIgnoresPriorityFrames), + ("testMultiplexerForwardsActiveToParent", testMultiplexerForwardsActiveToParent), + ("testCreatedChildChannelCanBeClosedImmediately", testCreatedChildChannelCanBeClosedImmediately), + ("testCreatedChildChannelCanBeClosedBeforeWritingHeaders", testCreatedChildChannelCanBeClosedBeforeWritingHeaders), + ("testCreatedChildChannelCanBeClosedImmediatelyWhenBaseIsActive", testCreatedChildChannelCanBeClosedImmediatelyWhenBaseIsActive), + ("testCreatedChildChannelCanBeClosedBeforeWritingHeadersWhenBaseIsActive", testCreatedChildChannelCanBeClosedBeforeWritingHeadersWhenBaseIsActive), + ("testMultiplexerCoalescesFlushCallsDuringChannelRead", testMultiplexerCoalescesFlushCallsDuringChannelRead), + ("testMultiplexerDoesntFireReadCompleteForEachFrame", testMultiplexerDoesntFireReadCompleteForEachFrame), + ("testMultiplexerCorrectlyTellsAllStreamsAboutReadComplete", testMultiplexerCorrectlyTellsAllStreamsAboutReadComplete), + ("testMultiplexerModifiesStreamChannelWritabilityBasedOnFixedSizeTokens", testMultiplexerModifiesStreamChannelWritabilityBasedOnFixedSizeTokens), + ("testMultiplexerModifiesStreamChannelWritabilityBasedOnParentChannelWritability", testMultiplexerModifiesStreamChannelWritabilityBasedOnParentChannelWritability), + ("testMultiplexerModifiesStreamChannelWritabilityBasedOnFixedSizeTokensAndChannelWritability", testMultiplexerModifiesStreamChannelWritabilityBasedOnFixedSizeTokensAndChannelWritability), + ("testStreamChannelToleratesFailingInitializer", testStreamChannelToleratesFailingInitializer), + ("testReadWhenUsingAutoreadOnChildChannel", testReadWhenUsingAutoreadOnChildChannel), + ("testStreamChannelSupportsSyncOptions", testStreamChannelSupportsSyncOptions), + ("testStreamErrorIsDeliveredToChannel", testStreamErrorIsDeliveredToChannel), + ("testPendingReadsAreFlushedEvenWithoutUnsatisfiedReadOnChannelInactive", testPendingReadsAreFlushedEvenWithoutUnsatisfiedReadOnChannelInactive), + ] + } +} + diff --git a/Tests/NIOHTTP2Tests/HTTP2InlineStreamMultiplexerTests.swift b/Tests/NIOHTTP2Tests/HTTP2InlineStreamMultiplexerTests.swift new file mode 100644 index 0000000..df796fe --- /dev/null +++ b/Tests/NIOHTTP2Tests/HTTP2InlineStreamMultiplexerTests.swift @@ -0,0 +1,1966 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2017-2023 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import XCTest +import Atomics +import NIOConcurrencyHelpers +import NIOCore +import NIOEmbedded +import NIOHTTP1 +@testable import NIOHPACK // for HPACKHeaders initializers +@testable import NIOHTTP2 + +private extension Channel { + /// Adds a simple no-op ``HTTP2StreamMultiplexer`` to the pipeline. + func addNoOpInlineMultiplexer(mode: NIOHTTP2Handler.ParserMode, eventLoop: EventLoop) { + XCTAssertNoThrow(try self.pipeline.addHandler(NIOHTTP2Handler(mode: mode, eventLoop: eventLoop) { channel in + self.eventLoop.makeSucceededFuture(()) + }).wait()) + } +} + +private struct MyError: Error { } + +typealias IODataWriteRecorder = WriteRecorder + +extension IODataWriteRecorder { + func drainConnectionSetupWrites(mode: NIOHTTP2Handler.ParserMode = .server) throws { + var frameDecoder = HTTP2FrameDecoder(allocator: ByteBufferAllocator(), expectClientMagic: mode == .client) + + while self.flushedWrites.count > 0 { + let write = self.flushedWrites.removeFirst() + guard case .byteBuffer(let buffer) = write else { + preconditionFailure("Unexpected write type.") + } + frameDecoder.append(bytes: buffer) + } + + // settings + guard case .settings = try frameDecoder.nextFrame()!.0.payload else { + XCTFail("Failed to decode expected settings.") + return + } + + if mode == .server { + // settings ACK + guard case .settings = try frameDecoder.nextFrame()!.0.payload else { + XCTFail("Failed to decode expected settings ACK.") + return + } + } + } +} + +extension HPACKHeaders { + static let basicRequestHeaders = HPACKHeaders(headers: [.init(name: ":path", value: "/"), .init(name: ":method", value: "GET"), .init(name: ":scheme", value: "HTTP/2.0")]) + static let basicResponseHeaders = HPACKHeaders(headers: [.init(name: ":status", value: "200")]) +} + +final class HTTP2InlineStreamMultiplexerTests: XCTestCase { + var channel: EmbeddedChannel! + let allocator = ByteBufferAllocator() + + override func setUp() { + self.channel = EmbeddedChannel() + } + + override func tearDown() { + self.channel = nil + } + + func connectionSetup(mode: NIOHTTP2Handler.ParserMode = .server) throws { + var frameEncoder = HTTP2FrameEncoder(allocator: channel.allocator) + var buffer = channel.allocator.buffer(capacity: 1024) + + self.channel.pipeline.connect(to: try .init(unixDomainSocketPath: "/no/such/path"), promise: nil) + + // We'll receive the preamble from the peer, which is normal. + let newSettings: HTTP2Settings = [] + let settings = HTTP2Frame(streamID: 0, payload: .settings(.settings(newSettings))) + + if mode == .server { + buffer.writeString("PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n") + } + XCTAssertNil(try frameEncoder.encode(frame: settings, to: &buffer)) + XCTAssertNil(try frameEncoder.encode(frame: HTTP2Frame(streamID: 0, payload: .settings(.ack)), to: &buffer)) + try channel.writeInbound(buffer) + + // receive settings + guard case .settings = try self.channel.assertReceivedFrame().payload else { + preconditionFailure() + } + // receive settings ack + guard case .settings = try self.channel.assertReceivedFrame().payload else { + preconditionFailure() + } + } + + // a ChannelInboundHandler which executes the provided closure on channelRead + class TestHookHandler: ChannelInboundHandler { + typealias InboundIn = HTTP2Frame.FramePayload + typealias OutboundOut = HTTP2Frame.FramePayload + + let channelReadHook: (ChannelHandlerContext, HTTP2Frame.FramePayload) -> () + + init(channelReadHook: @escaping (ChannelHandlerContext, HTTP2Frame.FramePayload) -> Void) { + self.channelReadHook = channelReadHook + } + + func channelRead(context: ChannelHandlerContext, data: NIOAny) { + let payload = self.unwrapInboundIn(data) + self.channelReadHook(context, payload) + } + } + + func testMultiplexerIgnoresFramesOnStream0() throws { + self.channel.addNoOpInlineMultiplexer(mode: .server, eventLoop: self.channel.eventLoop) + XCTAssertNoThrow(try connectionSetup()) + + let simplePingFrame = HTTP2Frame(streamID: .rootStream, payload: .ping(HTTP2PingData(withInteger: 5), ack: false)) + XCTAssertNoThrow(try self.channel.writeInbound(simplePingFrame.encode())) + XCTAssertNoThrow(try self.channel.assertReceivedFrame().assertFrameMatches(this: simplePingFrame)) + + XCTAssertNoThrow(try self.channel.finish()) + } + + func testHeadersFramesCreateNewChannels() throws { + let channelCount = ManagedAtomic(0) + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { channel in + channelCount.wrappingIncrement(ordering: .sequentiallyConsistent) + return channel.close() + } + + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + XCTAssertNoThrow(try connectionSetup()) + + // Let's send a bunch of headers frames. + for streamID in stride(from: 1, to: 100, by: 2) { + let frame = HTTP2Frame(streamID: HTTP2StreamID(streamID), payload: HTTP2Frame.FramePayload.headers(.init(headers: .basicRequestHeaders))) + XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) + } + + XCTAssertEqual(channelCount.load(ordering: .sequentiallyConsistent), 50) + XCTAssertNoThrow(try self.channel.finish()) + } + + func testChannelsCloseThemselvesWhenToldTo() throws { + let completedChannelCount = ManagedAtomic(0) + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { channel in + channel.closeFuture.whenSuccess { completedChannelCount.wrappingIncrement(ordering: .sequentiallyConsistent) } + return channel.pipeline.addHandler(TestHookHandler() { context, payload in + guard case .headers(let requestHeaders) = payload else { + preconditionFailure("Expected request headers.") + } + XCTAssertEqual(requestHeaders.headers, .basicRequestHeaders) + + let headers = HTTP2Frame.FramePayload.headers(.init(headers: .basicResponseHeaders, endStream: true)) + context.writeAndFlush(NIOAny(headers), promise: nil) + }) + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + XCTAssertNoThrow(try connectionSetup()) + + // Let's send a bunch of headers frames with endStream on them. This should open some streams. + let headers = HTTP2Frame.FramePayload.headers(.init(headers: .basicRequestHeaders, endStream: true)) + let streamIDs = stride(from: 1, to: 100, by: 2).map { HTTP2StreamID($0) } + for streamID in streamIDs { + XCTAssertNoThrow(try self.channel.writeInbound(HTTP2Frame(streamID: streamID, payload: headers).encode())) + } + XCTAssertEqual(completedChannelCount.load(ordering: .sequentiallyConsistent), 0) + + (self.channel.eventLoop as! EmbeddedEventLoop).run() + + // At this stage all the promises should be completed. + XCTAssertEqual(completedChannelCount.load(ordering: .sequentiallyConsistent), 50) + XCTAssertNoThrow(try self.channel.finish()) + } + + func testChannelsCloseAfterResetStreamFrameFirstThenEvent() throws { + let closeError = NIOLockedValueBox(nil) + + XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) + + // First, set up the frames we want to send/receive. + let streamID = HTTP2StreamID(1) + let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders, endStream: true))) + let rstStreamFrame = HTTP2Frame(streamID: streamID, payload: .rstStream(.cancel)) + + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { channel in + closeError.withLockedValue { closeError in + XCTAssertNil(closeError) + } + channel.closeFuture.whenFailure { failureError in + closeError.withLockedValue { closeError in + closeError = failureError + } + } + return channel.pipeline.addHandler(FramePayloadExpecter(expectedPayload: [frame.payload, rstStreamFrame.payload])) + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + XCTAssertNoThrow(try connectionSetup()) + + // Let's open the stream up. + XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) + closeError.withLockedValue { closeError in + XCTAssertNil(closeError) + } + + // Now we can send a RST_STREAM frame. + XCTAssertNoThrow(try self.channel.writeInbound(rstStreamFrame.encode())) + + (self.channel.eventLoop as! EmbeddedEventLoop).run() + + // At this stage the stream should be closed with the appropriate error code. + closeError.withLockedValue { error in + XCTAssertEqual(error as? NIOHTTP2Errors.StreamClosed, + NIOHTTP2Errors.streamClosed(streamID: streamID, errorCode: .cancel)) + } + XCTAssertNoThrow(try self.channel.finish()) + } + + func testChannelsCloseAfterGoawayFrameFirstThenEvent() throws { + // First, set up the frames we want to send/receive. + let streamID = HTTP2StreamID(1) + let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders, endStream: true))) + let goAwayFrame = HTTP2Frame(streamID: .rootStream, payload: .goAway(lastStreamID: .rootStream, errorCode: .http11Required, opaqueData: nil)) + + let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: self.channel.eventLoop) { channel in + XCTFail() + return channel.eventLoop.makeSucceededVoidFuture() + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + XCTAssertNoThrow(try connectionSetup(mode: .client)) + + // Let's open the stream up. + let multiplexer = try http2Handler.multiplexer.wait() + let streamFuture = multiplexer.createStreamChannel { channel in + return channel.eventLoop.makeSucceededVoidFuture() + } + + (self.channel.eventLoop as! EmbeddedEventLoop).run() + + let stream = try streamFuture.wait() + + stream.writeAndFlush(frame.payload, promise: nil) + + // Now we can send a GOAWAY frame. This will close the stream. + XCTAssertNoThrow(try self.channel.writeInbound(goAwayFrame.encode())) + + (self.channel.eventLoop as! EmbeddedEventLoop).run() + + XCTAssertThrowsError(try stream.closeFuture.wait()) { closeError in + XCTAssertEqual(closeError as? NIOHTTP2Errors.StreamClosed, + NIOHTTP2Errors.streamClosed(streamID: streamID, errorCode: .cancel)) + } + // At this stage the stream should be closed with the appropriate manufactured error code. + XCTAssertNoThrow(try self.channel.finish()) + } + + func testClosingIdleChannels() throws { + let frameReceiver = IODataWriteRecorder() + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { channel in + return channel.close() + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(frameReceiver).wait()) + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + XCTAssertNoThrow(try connectionSetup()) + try frameReceiver.drainConnectionSetupWrites() + + // Let's send a bunch of headers frames. These will all be answered by RST_STREAM frames. + let streamIDs = stride(from: 1, to: 100, by: 2).map { HTTP2StreamID($0) } + for streamID in streamIDs { + let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders))) + XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) + } + + let expectedFrames = streamIDs.map { HTTP2Frame(streamID: $0, payload: .rstStream(.cancel)) } + XCTAssertEqual(expectedFrames.count, frameReceiver.flushedWrites.count) + + var frameDecoder = HTTP2FrameDecoder(allocator: channel.allocator, expectClientMagic: false) + for (idx, expectedFrame) in expectedFrames.enumerated() { + if case .byteBuffer(let flushedWriteBuffer) = frameReceiver.flushedWrites[idx] { + frameDecoder.append(bytes: flushedWriteBuffer) + } + let (actualFrame, _) = try frameDecoder.nextFrame()! + expectedFrame.assertFrameMatches(this: actualFrame) + } + XCTAssertNoThrow(try self.channel.finish()) + } + + func testClosingActiveChannels() throws { + let frameReceiver = IODataWriteRecorder() + let channelPromise: EventLoopPromise = self.channel.eventLoop.makePromise() + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { channel in + channelPromise.succeed(channel) + return channel.eventLoop.makeSucceededFuture(()) + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(frameReceiver).wait()) + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + XCTAssertNoThrow(try connectionSetup()) + try frameReceiver.drainConnectionSetupWrites() + + XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) + + // Let's send a headers frame to open the stream. + let streamID = HTTP2StreamID(1) + let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders))) + XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) + + // The channel should now be active. + let childChannel = try channelPromise.futureResult.wait() + XCTAssertTrue(childChannel.isActive) + + // Now we close it. This triggers a RST_STREAM frame. + childChannel.close(promise: nil) + XCTAssertEqual(frameReceiver.flushedWrites.count, 1) + var frameDecoder = HTTP2FrameDecoder(allocator: channel.allocator, expectClientMagic: false) + if case .byteBuffer(let flushedWriteBuffer) = frameReceiver.flushedWrites[0] { + frameDecoder.append(bytes: flushedWriteBuffer) + } + let (flushedFrame, _) = try frameDecoder.nextFrame()! + flushedFrame.assertRstStreamFrame(streamID: streamID, errorCode: .cancel) + + XCTAssertNoThrow(try self.channel.finish()) + } + + func testClosePromiseIsSatisfied() throws { + let frameReceiver = IODataWriteRecorder() + let channelPromise: EventLoopPromise = self.channel.eventLoop.makePromise() + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { channel in + channelPromise.succeed(channel) + return channel.eventLoop.makeSucceededFuture(()) + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(frameReceiver).wait()) + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + XCTAssertNoThrow(try connectionSetup()) + try frameReceiver.drainConnectionSetupWrites() + + XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) + + // Let's send a headers frame to open the stream. + let streamID = HTTP2StreamID(1) + let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders))) + XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) + + // The channel should now be active. + let childChannel = try channelPromise.futureResult.wait() + XCTAssertTrue(childChannel.isActive) + + // Now we close it. This triggers a RST_STREAM frame. The channel will not be closed at this time. + var closed = false + childChannel.close().whenComplete { _ in closed = true } + XCTAssertEqual(frameReceiver.flushedWrites.count, 1) + var frameDecoder = HTTP2FrameDecoder(allocator: channel.allocator, expectClientMagic: false) + if case .byteBuffer(let flushedWriteBuffer) = frameReceiver.flushedWrites[0] { + frameDecoder.append(bytes: flushedWriteBuffer) + } + let (flushedFrame, _) = try frameDecoder.nextFrame()! + flushedFrame.assertRstStreamFrame(streamID: streamID, errorCode: .cancel) + XCTAssertTrue(closed) + } + + func testMultipleClosePromisesAreSatisfied() throws { + let frameReceiver = IODataWriteRecorder() + let channelPromise: EventLoopPromise = self.channel.eventLoop.makePromise() + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { channel in + channelPromise.succeed(channel) + return channel.eventLoop.makeSucceededFuture(()) + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(frameReceiver).wait()) + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + XCTAssertNoThrow(try connectionSetup()) + try frameReceiver.drainConnectionSetupWrites() + + // Let's send a headers frame to open the stream. + let streamID = HTTP2StreamID(1) + let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders))) + XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) + + // The channel should now be active. + let childChannel = try channelPromise.futureResult.wait() + XCTAssertTrue(childChannel.isActive) + + // Now we close it several times. This triggers one RST_STREAM frame. The channel will not be closed at this time. + var firstClosed = false + var secondClosed = false + var thirdClosed = false + childChannel.close().whenComplete { _ in + XCTAssertFalse(firstClosed) + XCTAssertFalse(secondClosed) + XCTAssertFalse(thirdClosed) + firstClosed = true + } + childChannel.close().whenComplete { _ in + XCTAssertTrue(firstClosed) + XCTAssertFalse(secondClosed) + XCTAssertFalse(thirdClosed) + secondClosed = true + } + childChannel.close().whenComplete { _ in + XCTAssertTrue(firstClosed) + XCTAssertTrue(secondClosed) + XCTAssertFalse(thirdClosed) + thirdClosed = true + } + XCTAssertEqual(frameReceiver.flushedWrites.count, 1) + var frameDecoder = HTTP2FrameDecoder(allocator: channel.allocator, expectClientMagic: false) + if case .byteBuffer(let flushedWriteBuffer) = frameReceiver.flushedWrites[0] { + frameDecoder.append(bytes: flushedWriteBuffer) + } + let (flushedFrame, _) = try frameDecoder.nextFrame()! + flushedFrame.assertRstStreamFrame(streamID: streamID, errorCode: .cancel) + XCTAssertTrue(thirdClosed) + + XCTAssertNoThrow(try self.channel.finish()) + } + + func testClosePromiseFailsWithError() throws { + let frameReceiver = IODataWriteRecorder() + let channelPromise: EventLoopPromise = self.channel.eventLoop.makePromise() + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { channel in + channelPromise.succeed(channel) + return channel.eventLoop.makeSucceededFuture(()) + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(frameReceiver).wait()) + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + XCTAssertNoThrow(try connectionSetup()) + try frameReceiver.drainConnectionSetupWrites() + + // Let's send a headers frame to open the stream. + let streamID = HTTP2StreamID(1) + let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders))) + XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) + + // The channel should now be active. + let childChannel = try channelPromise.futureResult.wait() + XCTAssertTrue(childChannel.isActive) + + // Now we close it. This triggers a RST_STREAM frame. The channel will not be closed at this time. + var closeError: Error? = nil + childChannel.close().whenFailure { closeError = $0 } + XCTAssertEqual(frameReceiver.flushedWrites.count, 1) + var frameDecoder = HTTP2FrameDecoder(allocator: channel.allocator, expectClientMagic: false) + if case .byteBuffer(let flushedWriteBuffer) = frameReceiver.flushedWrites[0] { + frameDecoder.append(bytes: flushedWriteBuffer) + } + let (flushedFrame, _) = try frameDecoder.nextFrame()! + flushedFrame.assertRstStreamFrame(streamID: streamID, errorCode: .cancel) + XCTAssertEqual(closeError as? NIOHTTP2Errors.StreamClosed, NIOHTTP2Errors.streamClosed(streamID: streamID, errorCode: .cancel)) + + XCTAssertNoThrow(try self.channel.finish()) + } + + func testFramesAreNotDeliveredUntilStreamIsSetUp() throws { + let channelPromise: EventLoopPromise = self.channel.eventLoop.makePromise() + let setupCompletePromise: EventLoopPromise = self.channel.eventLoop.makePromise() + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { channel in + channelPromise.succeed(channel) + return channel.pipeline.addHandler(InboundFramePayloadRecorder()).flatMap { + setupCompletePromise.futureResult + } + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + XCTAssertNoThrow(try connectionSetup()) + + // Let's send a headers frame to open the stream. + let streamID = HTTP2StreamID(1) + let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders))) + XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) + + // The channel should now be available, but no frames should have been received on either the parent or child channel. + let childChannel = try channelPromise.futureResult.wait() + let frameRecorder = try childChannel.pipeline.handler(type: InboundFramePayloadRecorder.self).wait() + self.channel.assertNoFramesReceived() + XCTAssertEqual(frameRecorder.receivedFrames.count, 0) + + // Send a few data frames for this stream, which should also not go through. + let dataFrame = HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(ByteBuffer(string: "Hello, world!"))))) + for _ in 0..<5 { + XCTAssertNoThrow(try self.channel.writeInbound(dataFrame.encode())) + } + self.channel.assertNoFramesReceived() + XCTAssertEqual(frameRecorder.receivedFrames.count, 0) + + // Use a PING frame to check that the channel is still functioning. + let ping = HTTP2Frame(streamID: .rootStream, payload: .ping(HTTP2PingData(withInteger: 5), ack: false)) + XCTAssertNoThrow(try self.channel.writeInbound(ping.encode())) + try self.channel.assertReceivedFrame().assertPingFrameMatches(this: ping) + self.channel.assertNoFramesReceived() + XCTAssertEqual(frameRecorder.receivedFrames.count, 0) + + // Ok, complete the setup promise. This should trigger all the frames to be delivered. + setupCompletePromise.succeed(()) + self.channel.assertNoFramesReceived() + XCTAssertEqual(frameRecorder.receivedFrames.count, 6) + frameRecorder.receivedFrames[0].assertHeadersFramePayloadMatches(this: frame.payload) + for idx in 1...5 { + frameRecorder.receivedFrames[idx].assertDataFramePayloadMatches(this: dataFrame.payload) + } + + XCTAssertNoThrow(try self.channel.finish()) + } + + func testFramesAreNotDeliveredIfSetUpFails() throws { + let writeRecorder = IODataWriteRecorder() + let channelPromise: EventLoopPromise = self.channel.eventLoop.makePromise() + let setupCompletePromise: EventLoopPromise = self.channel.eventLoop.makePromise() + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { channel in + channelPromise.succeed(channel) + return channel.pipeline.addHandler(InboundFramePayloadRecorder()).flatMap { + setupCompletePromise.futureResult + } + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(writeRecorder).wait()) + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + XCTAssertNoThrow(try connectionSetup()) + try writeRecorder.drainConnectionSetupWrites() + + // Let's send a headers frame to open the stream, along with some DATA frames. + let streamID = HTTP2StreamID(1) + let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders))) + XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) + + let dataFrame = try HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(ByteBuffer(string: "Hello, world!"))))).encode() + for _ in 0..<5 { + XCTAssertNoThrow(try self.channel.writeInbound(dataFrame)) + } + + // The channel should now be available, but no frames should have been received on either the parent or child channel. + let childChannel = try channelPromise.futureResult.wait() + let frameRecorder = try childChannel.pipeline.handler(type: InboundFramePayloadRecorder.self).wait() + self.channel.assertNoFramesReceived() + XCTAssertEqual(frameRecorder.receivedFrames.count, 0) + + // Ok, fail the setup promise. This should deliver a RST_STREAM frame, but not yet close the channel. + // The channel should, however, be inactive. + var channelClosed = false + childChannel.closeFuture.whenComplete { _ in channelClosed = true } + XCTAssertEqual(writeRecorder.flushedWrites.count, 0) + XCTAssertFalse(channelClosed) + + setupCompletePromise.fail(MyError()) + self.channel.assertNoFramesReceived() + XCTAssertEqual(frameRecorder.receivedFrames.count, 0) + XCTAssertFalse(childChannel.isActive) + XCTAssertEqual(writeRecorder.flushedWrites.count, 1) + var frameDecoder = HTTP2FrameDecoder(allocator: channel.allocator, expectClientMagic: false) + if case .byteBuffer(let flushedWriteBuffer) = writeRecorder.flushedWrites[0] { + frameDecoder.append(bytes: flushedWriteBuffer) + } + let (flushedFrame, _) = try frameDecoder.nextFrame()! + flushedFrame.assertRstStreamFrame(streamID: streamID, errorCode: .cancel) + + // Even delivering a new DATA frame should do nothing. + XCTAssertNoThrow(try self.channel.writeInbound(dataFrame)) + XCTAssertEqual(frameRecorder.receivedFrames.count, 0) + + XCTAssertEqual(frameRecorder.receivedFrames.count, 0) + XCTAssertFalse(childChannel.isActive) + XCTAssertEqual(writeRecorder.flushedWrites.count, 1) + XCTAssertFalse(channelClosed) + + (childChannel.eventLoop as! EmbeddedEventLoop).run() + XCTAssertTrue(channelClosed) + + XCTAssertNoThrow(try self.channel.finish()) + } + + func testFlushingOneChannelDoesntFlushThemAll() throws { + let writeTracker = IODataWriteRecorder() + let channels = NIOLockedValueBox<[Channel]>([]) + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { channel in + channels.withLockedValue { channels in + channels.append(channel) + } + return channel.eventLoop.makeSucceededFuture(()) + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(writeTracker).wait()) + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + XCTAssertNoThrow(try connectionSetup()) + try writeTracker.drainConnectionSetupWrites() + + // Let's open two streams. + let firstStreamID = HTTP2StreamID(1) + let secondStreamID = HTTP2StreamID(3) + for streamID in [firstStreamID, secondStreamID] { + let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders, endStream: true))) + XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) + } + channels.withLockedValue { channels in + XCTAssertEqual(channels.count, 2) + } + + // We will now write a headers frame to each channel. Neither frame should be written to the connection. To verify this + // we will flush the parent channel. + for (idx, _) in [firstStreamID, secondStreamID].enumerated() { + let frame = HTTP2Frame.FramePayload.headers(.init(headers: .basicResponseHeaders)) + channels.withLockedValue { channels in + channels[idx].write(frame, promise: nil) + } + } + self.channel.flush() + XCTAssertEqual(writeTracker.flushedWrites.count, 0) + + // Now we're going to flush only the first child channel. This should cause one flushed write. + channels.withLockedValue { channels in + channels[0].flush() + } + XCTAssertEqual(writeTracker.flushedWrites.count, 1) + + // Now the other. + channels.withLockedValue { channels in + channels[1].flush() + } + XCTAssertEqual(writeTracker.flushedWrites.count, 2) + + XCTAssertNoThrow(try self.channel.finish()) + } + + func testUnflushedWritesFailOnError() throws { + let childChannel = NIOLockedValueBox(nil) + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { channel in + childChannel.withLockedValue { childChannel in + childChannel = channel + } + return channel.eventLoop.makeSucceededVoidFuture() + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + XCTAssertNoThrow(try connectionSetup()) + + // Let's open a stream. + let streamID = HTTP2StreamID(1) + let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders, endStream: true))) + XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) + XCTAssertNotNil(channel) + + // We will now write a headers frame to the channel, but don't flush it. + var writeError: Error? = nil + let responseFrame = HTTP2Frame.FramePayload.headers(.init(headers: .basicResponseHeaders)) + childChannel.withLockedValue { childChannel in + childChannel!.write(responseFrame).whenFailure { + writeError = $0 + } + } + XCTAssertNil(writeError) + + // write a reset stream frame to close stream + let resetFrame = HTTP2Frame(streamID: streamID, payload: .rstStream(.cancel)) + XCTAssertNoThrow(try self.channel.writeInbound(resetFrame.encode())) + + XCTAssertNotNil(writeError) + + XCTAssertNoThrow(try self.channel.finish()) + } + + func testWritesFailOnClosedStreamChannels() throws { + let childChannel = NIOLockedValueBox(nil) + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { channel in + childChannel.withLockedValue { childChannel in + childChannel = channel + } + return channel.pipeline.addHandler(TestHookHandler() { context, payload in + guard case .headers(let requestHeaders) = payload else { + preconditionFailure("Expected request headers.") + } + XCTAssertEqual(requestHeaders.headers, .basicRequestHeaders) + + let headers = HTTP2Frame.FramePayload.headers(.init(headers: .basicResponseHeaders, endStream: true)) + context.writeAndFlush(NIOAny(headers), promise: nil) + }) + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + XCTAssertNoThrow(try connectionSetup()) + + // Let's open a stream. + let streamID = HTTP2StreamID(1) + let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders, endStream: true))) + XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) + XCTAssertNotNil(channel) + + // We will now write a headers frame to the channel. This should fail immediately. + var writeError: Error? = nil + let responseFrame = HTTP2Frame.FramePayload.headers(.init(headers: .basicRequestHeaders)) + childChannel.withLockedValue { childChannel in + childChannel!.write(responseFrame).whenFailure { + writeError = $0 + } + } + XCTAssertEqual(writeError as? ChannelError, ChannelError.ioOnClosedChannel) + + XCTAssertNoThrow(try self.channel.finish()) + } + + func testReadPullsInAllFrames() throws { + let childChannel = NIOLockedValueBox(nil) + let frameRecorder = InboundFramePayloadRecorder() + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { channel -> EventLoopFuture in + childChannel.withLockedValue { childChannel in + childChannel = channel + } + + // We're going to disable autoRead on this channel. + return channel.getOption(ChannelOptions.autoRead).map { + XCTAssertTrue($0) + }.flatMap { + channel.setOption(ChannelOptions.autoRead, value: false) + }.flatMap { + channel.getOption(ChannelOptions.autoRead) + }.map { + XCTAssertFalse($0) + }.flatMap { + channel.pipeline.addHandler(frameRecorder) + } + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + XCTAssertNoThrow(try connectionSetup()) + + // Let's open a stream. + let streamID = HTTP2StreamID(1) + let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders))) + XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) + XCTAssertNotNil(childChannel) + + // Now we're going to deliver 5 data frames for this stream. + let payloadBuffer = ByteBuffer(string: "Hello, world!") + let dataFrame = try HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(payloadBuffer)))).encode() + for _ in 0..<5 { + XCTAssertNoThrow(try self.channel.writeInbound(dataFrame)) + } + + // These frames should not have been delivered. + XCTAssertEqual(frameRecorder.receivedFrames.count, 0) + + // We'll call read() on the child channel. + childChannel.withLockedValue { childChannel in + childChannel!.read() + } + + // All frames should now have been delivered. + XCTAssertEqual(frameRecorder.receivedFrames.count, 6) + frameRecorder.receivedFrames[0].assertFramePayloadMatches(this: frame.payload) + for idx in 1...5 { + frameRecorder.receivedFrames[idx].assertDataFramePayload(endStream: false, payload: payloadBuffer) + } + + XCTAssertNoThrow(try self.channel.finish()) + } + + func testReadIsPerChannel() throws { + let firstStreamID = HTTP2StreamID(1) + let secondStreamID = HTTP2StreamID(3) + + // We don't have access to the streamID in the inbound stream initializer; we have to track + // the expected ID here. + let autoRead = ManagedAtomic(false) + let frameRecorders = NIOLockedValueBox<[HTTP2StreamID: InboundFramePayloadRecorder]>([:]) + + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { channel -> EventLoopFuture in + let recorder = InboundFramePayloadRecorder() + frameRecorders.withLockedValue { frameRecorders in + let expectedStreamID = frameRecorders.count * 2 + 1 + frameRecorders[HTTP2StreamID(expectedStreamID)] = recorder + } + + // We'll disable auto read on the first channel only. + let autoReadValue = autoRead.load(ordering: .sequentiallyConsistent) + autoRead.store(true, ordering: .sequentiallyConsistent) + + return channel.setOption(ChannelOptions.autoRead, value: autoReadValue).flatMap { + channel.pipeline.addHandler(recorder) + } + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + XCTAssertNoThrow(try connectionSetup()) + + // Let's open two streams. + for streamID in [firstStreamID, secondStreamID] { + let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders))) + XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) + } + + frameRecorders.withLockedValue { frameRecorders in + XCTAssertEqual(frameRecorders.count, 2) + // Stream 1 should not have received a frame, stream 3 should. + XCTAssertEqual(frameRecorders[firstStreamID]!.receivedFrames.count, 0) + XCTAssertEqual(frameRecorders[secondStreamID]!.receivedFrames.count, 1) + } + + // Deliver a DATA frame to each stream, which should also have gone into stream 3 but not stream 1. + let payloadBuffer = ByteBuffer(string: "Hello, world!") + for streamID in [firstStreamID, secondStreamID] { + let frame = HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(payloadBuffer)))) + XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) + } + + frameRecorders.withLockedValue { frameRecorders in + // Stream 1 should not have received a frame, stream 3 should. + XCTAssertEqual(frameRecorders[firstStreamID]!.receivedFrames.count, 0) + XCTAssertEqual(frameRecorders[secondStreamID]!.receivedFrames.count, 2) + } + + XCTAssertNoThrow(try self.channel.finish()) + } + + func testReadWillCauseAutomaticFrameDelivery() throws { + let childChannel = NIOLockedValueBox(nil) + let frameRecorder = InboundFramePayloadRecorder() + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { channel -> EventLoopFuture in + childChannel.withLockedValue { childChannel in + childChannel = channel + } + + // We're going to disable autoRead on this channel. + return channel.setOption(ChannelOptions.autoRead, value: false).flatMap { + channel.pipeline.addHandler(frameRecorder) + } + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + XCTAssertNoThrow(try connectionSetup()) + + // Let's open a stream. + let streamID = HTTP2StreamID(1) + let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders))) + XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) + XCTAssertNotNil(childChannel) + + // This stream should have seen no frames. + XCTAssertEqual(frameRecorder.receivedFrames.count, 0) + + // Call read, the header frame will come through. + childChannel.withLockedValue { childChannel in + childChannel!.read() + } + XCTAssertEqual(frameRecorder.receivedFrames.count, 1) + + // Call read again, nothing happens. + childChannel.withLockedValue { childChannel in + childChannel!.read() + } + XCTAssertEqual(frameRecorder.receivedFrames.count, 1) + + // Now deliver a data frame. + let dataFrame = try HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(ByteBuffer(string: "Hello, world!"))))).encode() + XCTAssertNoThrow(try self.channel.writeInbound(dataFrame)) + + // This frame should have been immediately delivered. + XCTAssertEqual(frameRecorder.receivedFrames.count, 2) + + // Delivering another data frame does nothing. + XCTAssertNoThrow(try self.channel.writeInbound(dataFrame)) + XCTAssertEqual(frameRecorder.receivedFrames.count, 2) + + XCTAssertNoThrow(try self.channel.finish()) + } + + func testReadWithNoPendingDataCausesReadOnParentChannel() throws { + let childChannel = NIOLockedValueBox(nil) + let readCounter = ReadCounter() + let frameRecorder = InboundFramePayloadRecorder() + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { channel -> EventLoopFuture in + childChannel.withLockedValue { childChannel in + childChannel = channel + } + + // We're going to disable autoRead on this channel. + return channel.setOption(ChannelOptions.autoRead, value: false).flatMap { + channel.pipeline.addHandler(frameRecorder) + } + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(readCounter).wait()) + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + XCTAssertNoThrow(try connectionSetup()) + + // Let's open a stream. + let streamID = HTTP2StreamID(1) + let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders))) + XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) + XCTAssertNotNil(childChannel) + + // This stream should have seen no frames. + XCTAssertEqual(frameRecorder.receivedFrames.count, 0) + + // There should be no calls to read. + XCTAssertEqual(readCounter.readCount, 0) + + // Call read, the header frame will come through. No calls to read on the parent stream. + childChannel.withLockedValue { childChannel in + childChannel!.read() + } + XCTAssertEqual(frameRecorder.receivedFrames.count, 1) + XCTAssertEqual(readCounter.readCount, 0) + + // Call read again, read is called on the parent stream. No frames delivered. + childChannel.withLockedValue { childChannel in + childChannel!.read() + } + XCTAssertEqual(frameRecorder.receivedFrames.count, 1) + XCTAssertEqual(readCounter.readCount, 1) + + // Now deliver a data frame. + let dataFrame = try HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(ByteBuffer(string: "Hello, world!"))))).encode() + XCTAssertNoThrow(try self.channel.writeInbound(dataFrame)) + + // This frame should have been immediately delivered. No extra call to read. + XCTAssertEqual(frameRecorder.receivedFrames.count, 2) + XCTAssertEqual(readCounter.readCount, 1) + + // Another call to read issues a read to the parent stream. + childChannel.withLockedValue { childChannel in + childChannel!.read() + } + XCTAssertEqual(frameRecorder.receivedFrames.count, 2) + XCTAssertEqual(readCounter.readCount, 2) + + // Another call to read, this time does not issue a read to the parent stream. + childChannel.withLockedValue { childChannel in + childChannel!.read() + } + XCTAssertEqual(frameRecorder.receivedFrames.count, 2) + XCTAssertEqual(readCounter.readCount, 2) + + // Delivering two more frames does not cause another call to read, and only one frame + // is delivered. + XCTAssertNoThrow(try self.channel.writeInbound(dataFrame)) + XCTAssertNoThrow(try self.channel.writeInbound(dataFrame)) + XCTAssertEqual(frameRecorder.receivedFrames.count, 3) + XCTAssertEqual(readCounter.readCount, 2) + + XCTAssertNoThrow(try self.channel.finish()) + } + + func testHandlersAreRemovedOnClosure() throws { + var handlerRemoved = false + let handlerRemovedPromise: EventLoopPromise = self.channel.eventLoop.makePromise() + handlerRemovedPromise.futureResult.whenComplete { _ in handlerRemoved = true } + + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { channel in + return channel.pipeline.addHandlers([ + HandlerRemovedHandler(removedPromise: handlerRemovedPromise), + TestHookHandler() { context, payload in + guard case .headers(let requestHeaders) = payload else { + preconditionFailure("Expected request headers.") + } + XCTAssertEqual(requestHeaders.headers, .basicRequestHeaders) + + let headers = HTTP2Frame.FramePayload.headers(.init(headers: .basicResponseHeaders, endStream: true)) + context.writeAndFlush(NIOAny(headers), promise: nil) + }]) + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + XCTAssertNoThrow(try connectionSetup()) + + // Let's open a stream. + let streamID = HTTP2StreamID(1) + let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders, endStream: true))) + XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) + + // No handlerRemoved so far. + XCTAssertFalse(handlerRemoved) + + // The handlers will only be removed after we spin the loop. + (self.channel.eventLoop as! EmbeddedEventLoop).run() + XCTAssertTrue(handlerRemoved) + + XCTAssertNoThrow(try self.channel.finish()) + } + + func testHandlersAreRemovedOnClosureWithError() throws { + var handlerRemoved = false + let handlerRemovedPromise: EventLoopPromise = self.channel.eventLoop.makePromise() + handlerRemovedPromise.futureResult.whenComplete { _ in handlerRemoved = true } + + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { channel in + return channel.pipeline.addHandlers([ + HandlerRemovedHandler(removedPromise: handlerRemovedPromise), + TestHookHandler() { context, payload in + guard case .headers(let requestHeaders) = payload else { + preconditionFailure("Expected request headers.") + } + XCTAssertEqual(requestHeaders.headers, .basicRequestHeaders) + + let headers = HTTP2Frame.FramePayload.headers(.init(headers: .basicResponseHeaders, endStream: true)) + context.writeAndFlush(NIOAny(headers), promise: nil) + }]) + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + XCTAssertNoThrow(try connectionSetup()) + + // Let's open a stream. + let streamID = HTTP2StreamID(1) + let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders, endStream: true))) + XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) + + // No handlerRemoved so far. + XCTAssertFalse(handlerRemoved) + + // The handlers will only be removed after we spin the loop. + (self.channel.eventLoop as! EmbeddedEventLoop).run() + XCTAssertTrue(handlerRemoved) + + XCTAssertNoThrow(try self.channel.finish()) + } + + func testCreatingOutboundChannelClient() throws { + let configurePromise: EventLoopPromise = self.channel.eventLoop.makePromise() + let createdChannelCount = ManagedAtomic(0) + var configuredChannelCount = 0 + var streamIDs = Array() + let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: self.channel.eventLoop) { _ in + XCTFail("Must not be called") + return self.channel.eventLoop.makeFailedFuture(MyError()) + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) // to make the channel active + + let multiplexer = try http2Handler.multiplexer.wait() + for _ in 0..<3 { + let channelPromise: EventLoopPromise = self.channel.eventLoop.makePromise() + multiplexer.createStreamChannel(promise: channelPromise) { channel in + createdChannelCount.wrappingIncrement(ordering: .sequentiallyConsistent) + return configurePromise.futureResult + } + channelPromise.futureResult.whenSuccess { channel in + configuredChannelCount += 1 + // Write some headers: the flush will trigger a stream ID to be assigned to the channel. + channel.writeAndFlush(HTTP2Frame.FramePayload.headers(.init(headers: .basicRequestHeaders))).whenSuccess { + channel.getOption(HTTP2StreamChannelOptions.streamID).whenSuccess { streamID in + streamIDs.append(streamID) + } + } + } + } + + XCTAssertEqual(createdChannelCount.load(ordering: .sequentiallyConsistent), 0) + XCTAssertEqual(configuredChannelCount, 0) + XCTAssertEqual(streamIDs.count, 0) + + (self.channel.eventLoop as! EmbeddedEventLoop).run() + XCTAssertEqual(createdChannelCount.load(ordering: .sequentiallyConsistent), 3) + XCTAssertEqual(configuredChannelCount, 0) + XCTAssertEqual(streamIDs.count, 0) + + configurePromise.succeed(()) + XCTAssertEqual(createdChannelCount.load(ordering: .sequentiallyConsistent), 3) + XCTAssertEqual(configuredChannelCount, 3) + XCTAssertEqual(streamIDs, [1, 3, 5].map { HTTP2StreamID($0) }) + + XCTAssertNoThrow(try self.channel.finish()) + } + + func testWritesOnCreatedChannelAreDelayed() throws { + let configurePromise: EventLoopPromise = self.channel.eventLoop.makePromise() + let writeRecorder = IODataWriteRecorder() + let childChannel = NIOLockedValueBox(nil) + + XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) + + let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: self.channel.eventLoop) { _ in + XCTFail("Must not be called") + return self.channel.eventLoop.makeFailedFuture(MyError()) + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(writeRecorder).wait()) + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + (self.channel.eventLoop as! EmbeddedEventLoop).run() + try writeRecorder.drainConnectionSetupWrites(mode: .client) + + let multiplexer = try http2Handler.multiplexer.wait() + multiplexer.createStreamChannel(promise: nil) { channel in + childChannel.withLockedValue { childChannel in + childChannel = channel + } + return configurePromise.futureResult + } + (self.channel.eventLoop as! EmbeddedEventLoop).run() + XCTAssertNotNil(childChannel) + + childChannel.withLockedValue { childChannel in + childChannel!.writeAndFlush(HTTP2Frame.FramePayload.headers(.init(headers: .basicRequestHeaders)), promise: nil) + } + XCTAssertEqual(writeRecorder.flushedWrites.count, 0) + + configurePromise.succeed(()) + (self.channel.eventLoop as! EmbeddedEventLoop).run() + XCTAssertEqual(writeRecorder.flushedWrites.count, 1) + + XCTAssertNoThrow(try self.channel.finish()) + } + + func testWritesAreCancelledOnFailingInitializer() throws { + let configurePromise: EventLoopPromise = self.channel.eventLoop.makePromise() + let childChannel = NIOLockedValueBox(nil) + + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { _ in + XCTFail("Must not be called") + return self.channel.eventLoop.makeFailedFuture(MyError()) + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + let multiplexer = try http2Handler.multiplexer.wait() + multiplexer.createStreamChannel(promise: nil) { channel in + childChannel.withLockedValue { childChannel in + childChannel = channel + } + return configurePromise.futureResult + } + (self.channel.eventLoop as! EmbeddedEventLoop).run() + + var writeError: Error? = nil + childChannel.withLockedValue { childChannel in + childChannel!.writeAndFlush(HTTP2Frame.FramePayload.headers(.init(headers: .basicRequestHeaders))).whenFailure { writeError = $0 } + } + XCTAssertNil(writeError) + + configurePromise.fail(MyError()) + XCTAssertNotNil(writeError) + XCTAssertTrue(writeError is MyError) + + XCTAssertNoThrow(try self.channel.finish()) + } + + func testFailingInitializerDoesNotWrite() throws { + let configurePromise: EventLoopPromise = self.channel.eventLoop.makePromise() + let writeRecorder = FrameWriteRecorder() + + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { _ in + XCTFail("Must not be called") + return self.channel.eventLoop.makeFailedFuture(MyError()) + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(writeRecorder).wait()) + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + let multiplexer = try http2Handler.multiplexer.wait() + multiplexer.createStreamChannel(promise: nil) { channel in + return configurePromise.futureResult + } + (self.channel.eventLoop as! EmbeddedEventLoop).run() + + configurePromise.fail(MyError()) + XCTAssertEqual(writeRecorder.flushedWrites.count, 0) + + XCTAssertNoThrow(try self.channel.finish()) + } + + func testCreatedChildChannelDoesNotActivateEarly() throws { + var activated = false + + let activePromise: EventLoopPromise = self.channel.eventLoop.makePromise() + let activeRecorder = ActiveHandler(activatedPromise: activePromise) + activePromise.futureResult.map { + activated = true + }.whenFailure { (_: Error) in + XCTFail("Activation promise must not fail") + } + + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { _ in + XCTFail("Must not be called") + return self.channel.eventLoop.makeFailedFuture(MyError()) + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + let multiplexer = try http2Handler.multiplexer.wait() + multiplexer.createStreamChannel(promise: nil) { channel in + return channel.pipeline.addHandler(activeRecorder) + } + (self.channel.eventLoop as! EmbeddedEventLoop).run() + XCTAssertFalse(activated) + + XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) + + XCTAssertTrue(activated) + + XCTAssertNoThrow(try self.channel.finish()) + } + + func testCreatedChildChannelActivatesIfParentIsActive() throws { + var activated = false + + let activePromise: EventLoopPromise = self.channel.eventLoop.makePromise() + let activeRecorder = ActiveHandler(activatedPromise: activePromise) + activePromise.futureResult.map { + activated = true + }.whenFailure { (_: Error) in + XCTFail("Activation promise must not fail") + } + + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { _ in + XCTFail("Must not be called") + return self.channel.eventLoop.makeFailedFuture(MyError()) + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + + XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 8765)).wait()) + XCTAssertFalse(activated) + + let multiplexer = try http2Handler.multiplexer.wait() + multiplexer.createStreamChannel(promise: nil) { channel in + return channel.pipeline.addHandler(activeRecorder) + } + (self.channel.eventLoop as! EmbeddedEventLoop).run() + XCTAssertTrue(activated) + + XCTAssertNoThrow(try self.channel.finish()) + } + + func testInitiatedChildChannelActivates() throws { + XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) + + var activated = false + + let activePromise: EventLoopPromise = self.channel.eventLoop.makePromise() + let activeRecorder = ActiveHandler(activatedPromise: activePromise) + activePromise.futureResult.map { + activated = true + }.whenFailure { (_: Error) in + XCTFail("Activation promise must not fail") + } + + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { channel in + return channel.pipeline.addHandler(activeRecorder) + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + XCTAssertNoThrow(try connectionSetup()) + self.channel.pipeline.fireChannelActive() + + // Open a new stream. + XCTAssertFalse(activated) + let streamID = HTTP2StreamID(1) + let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders))) + XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) + XCTAssertTrue(activated) + + XCTAssertNoThrow(try self.channel.finish()) + } + + func testMultiplexerIgnoresPriorityFrames() throws { + self.channel.addNoOpInlineMultiplexer(mode: .server, eventLoop: self.channel.eventLoop) + XCTAssertNoThrow(try connectionSetup()) + + let simplePingFrame = HTTP2Frame(streamID: 106, payload: .priority(.init(exclusive: true, dependency: .rootStream, weight: 15))) + XCTAssertNoThrow(try self.channel.writeInbound(simplePingFrame.encode())) + XCTAssertNoThrow(try self.channel.assertReceivedFrame().assertFrameMatches(this: simplePingFrame)) + + XCTAssertNoThrow(try self.channel.finish()) + } + + func testMultiplexerForwardsActiveToParent() throws { + self.channel.addNoOpInlineMultiplexer(mode: .client, eventLoop: self.channel.eventLoop) + + var didActivate = false + + let activePromise = self.channel.eventLoop.makePromise(of: Void.self) + activePromise.futureResult.whenSuccess { + didActivate = true + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(ActiveHandler(activatedPromise: activePromise)).wait()) + XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/nothing")).wait()) + XCTAssertTrue(didActivate) + + XCTAssertNoThrow(try self.channel.finish()) + } + + func testCreatedChildChannelCanBeClosedImmediately() throws { + let closed = ManagedAtomic(false) + + let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: self.channel.eventLoop) { channel in + XCTFail("Must not be called") + return self.channel.eventLoop.makeFailedFuture(MyError()) + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + + XCTAssertFalse(closed.load(ordering: .sequentiallyConsistent)) + let multiplexer = try http2Handler.multiplexer.wait() + multiplexer.createStreamChannel(promise: nil) { channel in + channel.close().whenComplete { _ in closed.store(true, ordering: .sequentiallyConsistent) } + return channel.eventLoop.makeSucceededFuture(()) + } + self.channel.embeddedEventLoop.run() + XCTAssertTrue(closed.load(ordering: .sequentiallyConsistent)) + XCTAssertNoThrow(XCTAssertTrue(try self.channel.finish().isClean)) + } + + func testCreatedChildChannelCanBeClosedBeforeWritingHeaders() throws { + var closed = false + + let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: self.channel.eventLoop) { channel in + XCTFail("Must not be called") + return self.channel.eventLoop.makeFailedFuture(MyError()) + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + + let channelPromise = self.channel.eventLoop.makePromise(of: Channel.self) + let multiplexer = try http2Handler.multiplexer.wait() + multiplexer.createStreamChannel(promise: channelPromise) { channel in + return channel.eventLoop.makeSucceededFuture(()) + } + self.channel.embeddedEventLoop.run() + + let child = try assertNoThrowWithValue(channelPromise.futureResult.wait()) + child.closeFuture.whenComplete { _ in closed = true } + + XCTAssertFalse(closed) + child.close(promise: nil) + self.channel.embeddedEventLoop.run() + XCTAssertTrue(closed) + XCTAssertNoThrow(XCTAssertTrue(try self.channel.finish().isClean)) + } + + func testCreatedChildChannelCanBeClosedImmediatelyWhenBaseIsActive() throws { + let closed = ManagedAtomic(false) + + // We need to activate the underlying channel here. + XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 80)).wait()) + + let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: self.channel.eventLoop) { channel in + XCTFail("Must not be called") + return self.channel.eventLoop.makeFailedFuture(MyError()) + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + XCTAssertEqual(try self.channel.readAllBuffers().count, 2) // magic & settings + + XCTAssertFalse(closed.load(ordering: .sequentiallyConsistent)) + let multiplexer = try http2Handler.multiplexer.wait() + multiplexer.createStreamChannel(promise: nil) { channel in + channel.close().whenComplete { _ in closed.store(true, ordering: .sequentiallyConsistent) } + return channel.eventLoop.makeSucceededFuture(()) + } + self.channel.embeddedEventLoop.run() + + XCTAssertTrue(closed.load(ordering: .sequentiallyConsistent)) + XCTAssertNoThrow(XCTAssertTrue(try self.channel.finish().isClean)) + } + + func testCreatedChildChannelCanBeClosedBeforeWritingHeadersWhenBaseIsActive() throws { + var closed = false + + // We need to activate the underlying channel here. + XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 80)).wait()) + + let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: self.channel.eventLoop) { channel in + XCTFail("Must not be called") + return self.channel.eventLoop.makeFailedFuture(MyError()) + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + XCTAssertEqual(try self.channel.readAllBuffers().count, 2) // magic & settings + + let channelPromise = self.channel.eventLoop.makePromise(of: Channel.self) + let multiplexer = try http2Handler.multiplexer.wait() + multiplexer.createStreamChannel(promise: channelPromise) { channel in + return channel.eventLoop.makeSucceededFuture(()) + } + self.channel.embeddedEventLoop.run() + + let child = try assertNoThrowWithValue(channelPromise.futureResult.wait()) + child.closeFuture.whenComplete { _ in closed = true } + + XCTAssertFalse(closed) + child.close(promise: nil) + self.channel.embeddedEventLoop.run() + + XCTAssertTrue(closed) + XCTAssertNoThrow(XCTAssertTrue(try self.channel.finish().isClean)) + } + + func testMultiplexerCoalescesFlushCallsDuringChannelRead() throws { + // Add a flush counter. + let flushCounter = FlushCounter() + XCTAssertNoThrow(try self.channel.pipeline.addHandler(flushCounter).wait()) + + // Add a server-mode multiplexer that will add an auto-response handler. + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { channel in + channel.pipeline.addHandler(QuickFramePayloadResponseHandler()) + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + XCTAssertNoThrow(try connectionSetup()) + + // We're going to send in 10 request frames. + let requestHeaders = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) + XCTAssertEqual(flushCounter.flushCount, 2) // two flushes in connection setup + + let framesToSend = stride(from: 1, through: 19, by: 2).map { HTTP2Frame(streamID: HTTP2StreamID($0), payload: .headers(.init(headers: requestHeaders, endStream: true))) } + for frame in framesToSend { + self.channel.pipeline.fireChannelRead(NIOAny(try frame.encode())) + } + self.channel.embeddedEventLoop.run() + + // Response frames should have been written, but no flushes, so they aren't visible. + XCTAssertEqual(try self.channel.decodedSentFrames().count, 2) // 2 for handler setup + XCTAssertEqual(flushCounter.flushCount, 2) // 2 for handler setup + + // Now send channel read complete. The frames should be flushed through. + self.channel.pipeline.fireChannelReadComplete() + XCTAssertEqual(try self.channel.decodedSentFrames().count, 10) + XCTAssertEqual(flushCounter.flushCount, 3) + } + + func testMultiplexerDoesntFireReadCompleteForEachFrame() throws { + let frameRecorder = InboundFramePayloadRecorder() + let readCompleteCounter = ReadCompleteCounter() + + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { childChannel in + return childChannel.pipeline.addHandler(frameRecorder).flatMap { + childChannel.pipeline.addHandler(readCompleteCounter) + } + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + XCTAssertNoThrow(try connectionSetup()) + + XCTAssertEqual(frameRecorder.receivedFrames.count, 0) + XCTAssertEqual(readCompleteCounter.readCompleteCount, 0) + + // Wake up and activate the stream. + let requestHeaders = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) + let requestFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: requestHeaders, endStream: false))) + XCTAssertNoThrow(self.channel.pipeline.fireChannelRead(NIOAny(try requestFrame.encode()))) + self.channel.embeddedEventLoop.run() + + XCTAssertEqual(frameRecorder.receivedFrames.count, 1) + XCTAssertEqual(readCompleteCounter.readCompleteCount, 1) + + // Now we're going to send 9 data frames. + let dataFrame = try HTTP2Frame(streamID: 1, payload: .data(.init(data: .byteBuffer(ByteBuffer(string: "Hello, world!"))))).encode() + for _ in 0..<9 { + self.channel.pipeline.fireChannelRead(NIOAny(dataFrame)) + } + + // We should have 1 read (the HEADERS), and one read complete. + XCTAssertEqual(frameRecorder.receivedFrames.count, 1) + XCTAssertEqual(readCompleteCounter.readCompleteCount, 1) + + // Fire read complete on the parent and it'll propagate to the child. This will trigger the reads. + self.channel.pipeline.fireChannelReadComplete() + + // We should have 10 reads, and two read completes. + XCTAssertEqual(frameRecorder.receivedFrames.count, 10) + XCTAssertEqual(readCompleteCounter.readCompleteCount, 2) + + // If we fire a new read complete on the parent, the child doesn't see it this time, as it received no frames. + self.channel.pipeline.fireChannelReadComplete() + XCTAssertEqual(frameRecorder.receivedFrames.count, 10) + XCTAssertEqual(readCompleteCounter.readCompleteCount, 2) + } + + func testMultiplexerCorrectlyTellsAllStreamsAboutReadComplete() throws { + // These are deliberately getting inserted to all streams. The test above confirms the single-stream + // behaviour is correct. + let frameRecorder = InboundFramePayloadRecorder() + let readCompleteCounter = ReadCompleteCounter() + + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { childChannel in + return childChannel.pipeline.addHandler(frameRecorder).flatMap { + childChannel.pipeline.addHandler(readCompleteCounter) + } + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + XCTAssertNoThrow(try connectionSetup()) + + XCTAssertEqual(frameRecorder.receivedFrames.count, 0) + XCTAssertEqual(readCompleteCounter.readCompleteCount, 0) + + // Wake up and activate the streams. + let requestHeaders = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) + for streamID in [HTTP2StreamID(1), HTTP2StreamID(3), HTTP2StreamID(5)] { + let requestFrame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: requestHeaders, endStream: false))) + try self.channel.pipeline.fireChannelRead(NIOAny(requestFrame.encode())) + } + self.channel.embeddedEventLoop.run() + + XCTAssertEqual(frameRecorder.receivedFrames.count, 3) + XCTAssertEqual(readCompleteCounter.readCompleteCount, 3) + + // Firing in readComplete does not cause a second readComplete for each stream, as no frames were delivered. + self.channel.pipeline.fireChannelReadComplete() + XCTAssertEqual(frameRecorder.receivedFrames.count, 3) + XCTAssertEqual(readCompleteCounter.readCompleteCount, 3) + + // Now we're going to send a data frame on stream 1. + let dataFrame = HTTP2Frame(streamID: 1, payload: .data(.init(data: .byteBuffer(ByteBuffer(string: "Hello, world!"))))) + self.channel.pipeline.fireChannelRead(NIOAny(try dataFrame.encode())) + + // We should have 3 reads, and 3 read completes. The frame is not delivered as we have no frame fast-path. + XCTAssertEqual(frameRecorder.receivedFrames.count, 3) + XCTAssertEqual(readCompleteCounter.readCompleteCount, 3) + + // Fire read complete on the parent and it'll propagate to the child, but only to the one + // that saw a frame. + self.channel.pipeline.fireChannelReadComplete() + + // We should have 4 reads, and 4 read completes. + XCTAssertEqual(frameRecorder.receivedFrames.count, 4) + XCTAssertEqual(readCompleteCounter.readCompleteCount, 4) + + // If we fire a new read complete on the parent, the children don't see it. + self.channel.pipeline.fireChannelReadComplete() + XCTAssertEqual(frameRecorder.receivedFrames.count, 4) + XCTAssertEqual(readCompleteCounter.readCompleteCount, 4) + } + + func testMultiplexerModifiesStreamChannelWritabilityBasedOnFixedSizeTokens() throws { + var streamConfiguration = NIOHTTP2Handler.StreamConfiguration() + streamConfiguration.outboundBufferSizeHighWatermark = 100 + streamConfiguration.outboundBufferSizeLowWatermark = 50 + let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: self.channel.eventLoop, streamConfiguration: streamConfiguration) { _ in + XCTFail("Must not be called") + return self.channel.eventLoop.makeFailedFuture(MyError()) + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + + // We need to activate the underlying channel here. + XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 80)).wait()) + + // Now we want to create a new child stream. + let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) + let multiplexer = try http2Handler.multiplexer.wait() + multiplexer.createStreamChannel(promise: childChannelPromise) { childChannel in + return childChannel.eventLoop.makeSucceededFuture(()) + } + self.channel.embeddedEventLoop.run() + + let childChannel = try assertNoThrowWithValue(childChannelPromise.futureResult.wait()) + XCTAssertTrue(childChannel.isWritable) + + // We're going to write a HEADERS frame (9 bytes) and an 81 byte DATA frame (90 bytes). This will not flip the + // writability state. + let headers = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) + let headersFrame = HTTP2Frame.FramePayload.headers(.init(headers: headers, endStream: false)) + + var dataBuffer = childChannel.allocator.buffer(capacity: 81) + dataBuffer.writeBytes(repeatElement(0, count: 81)) + let dataFrame = HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(dataBuffer), endStream: false)) + + childChannel.write(headersFrame, promise: nil) + childChannel.write(dataFrame, promise: nil) + XCTAssertTrue(childChannel.isWritable) + + // Now we're going to send another HEADERS frame (for trailers). This should flip the channel writability. + let trailers = HPACKHeaders([]) + let trailersFrame = HTTP2Frame.FramePayload.headers(.init(headers: trailers, endStream: true)) + childChannel.write(trailersFrame, promise: nil) + XCTAssertFalse(childChannel.isWritable) + + // Now we flush the writes. This flips the writability again. + childChannel.flush() + XCTAssertTrue(childChannel.isWritable) + } + + func testMultiplexerModifiesStreamChannelWritabilityBasedOnParentChannelWritability() throws { + let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: self.channel.eventLoop) { _ in + XCTFail("Must not be called") + return self.channel.eventLoop.makeFailedFuture(MyError()) + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + + // We need to activate the underlying channel here. + XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 80)).wait()) + + // Now we want to create a few new child streams. + let promises = (0..<5).map { _ in self.channel.eventLoop.makePromise(of: Channel.self) } + for promise in promises { + let multiplexer = try http2Handler.multiplexer.wait() + multiplexer.createStreamChannel(promise: promise) { childChannel in + return childChannel.eventLoop.makeSucceededFuture(()) + } + } + self.channel.embeddedEventLoop.run() + + let channels = try assertNoThrowWithValue(promises.map { promise in try promise.futureResult.wait() }) + + // These are all writable. + XCTAssertEqual(channels.map { $0.isWritable }, [true, true, true, true, true]) + + // We need to write (and flush) some data so that the streams get stream IDs. + for childChannel in channels { + XCTAssertNoThrow(try childChannel.writeAndFlush(HTTP2Frame.FramePayload.headers(.init(headers: .basicRequestHeaders))).wait()) + } + + // Mark the parent channel not writable. This currently changes nothing. + self.channel.isWritable = false + self.channel.pipeline.fireChannelWritabilityChanged() + + // All are now non-writable. + XCTAssertEqual(channels.map { $0.isWritable }, [false, false, false, false, false]) + + // And back again. + self.channel.isWritable = true + self.channel.pipeline.fireChannelWritabilityChanged() + XCTAssertEqual(channels.map { $0.isWritable }, [true, true, true, true, true]) + } + + func testMultiplexerModifiesStreamChannelWritabilityBasedOnFixedSizeTokensAndChannelWritability() throws { + var streamConfiguration = NIOHTTP2Handler.StreamConfiguration() + streamConfiguration.outboundBufferSizeHighWatermark = 100 + streamConfiguration.outboundBufferSizeLowWatermark = 50 + let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: self.channel.eventLoop, streamConfiguration: streamConfiguration) { _ in + XCTFail("Must not be called") + return self.channel.eventLoop.makeFailedFuture(MyError()) + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + + // We need to activate the underlying channel here. + XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 80)).wait()) + + // Now we want to create a new child stream. + let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) + let multiplexer = try http2Handler.multiplexer.wait() + multiplexer.createStreamChannel(promise: childChannelPromise) { childChannel in + return childChannel.eventLoop.makeSucceededFuture(()) + } + self.channel.embeddedEventLoop.run() + + let childChannel = try assertNoThrowWithValue(childChannelPromise.futureResult.wait()) + // We need to write (and flush) some data so that the streams get stream IDs. + XCTAssertNoThrow(try childChannel.writeAndFlush(HTTP2Frame.FramePayload.headers(.init(headers: .basicRequestHeaders))).wait()) + + XCTAssertTrue(childChannel.isWritable) + + // We're going to write a HEADERS frame (9 bytes) and an 81 byte DATA frame (90 bytes). This will not flip the + // writability state. + let headers = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) + let headersPayload = HTTP2Frame.FramePayload.headers(.init(headers: headers, endStream: false)) + + var dataBuffer = childChannel.allocator.buffer(capacity: 81) + dataBuffer.writeBytes(repeatElement(0, count: 81)) + let dataPayload = HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(dataBuffer), endStream: false)) + + childChannel.write(headersPayload, promise: nil) + childChannel.write(dataPayload, promise: nil) + XCTAssertTrue(childChannel.isWritable) + + // Now we're going to send another HEADERS frame (for trailers). This should flip the channel writability. + let trailers = HPACKHeaders([]) + let trailersPayload = HTTP2Frame.FramePayload.headers(.init(headers: trailers, endStream: true)) + childChannel.write(trailersPayload, promise: nil) + XCTAssertFalse(childChannel.isWritable) + + // Now mark the channel not writable. + self.channel.isWritable = false + self.channel.pipeline.fireChannelWritabilityChanged() + + // Now we flush the writes. The channel remains not writable. + childChannel.flush() + XCTAssertFalse(childChannel.isWritable) + + // Now we mark the parent channel writable. This flips the writability state. + self.channel.isWritable = true + self.channel.pipeline.fireChannelWritabilityChanged() + XCTAssertTrue(childChannel.isWritable) + } + + func testStreamChannelToleratesFailingInitializer() throws { + struct DummyError: Error {} + var streamConfiguration = NIOHTTP2Handler.StreamConfiguration() + streamConfiguration.outboundBufferSizeHighWatermark = 100 + streamConfiguration.outboundBufferSizeLowWatermark = 50 + let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: self.channel.eventLoop, streamConfiguration: streamConfiguration) { _ in + XCTFail("Must not be called") + return self.channel.eventLoop.makeFailedFuture(MyError()) + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + + // We need to activate the underlying channel here. + XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(ipAddress: "1.2.3.4", port: 5)).wait()) + + // Now we want to create a new child stream. + let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) + let multiplexer = try http2Handler.multiplexer.wait() + multiplexer.createStreamChannel(promise: childChannelPromise) { childChannel in + childChannel.close().flatMap { + childChannel.eventLoop.makeFailedFuture(DummyError()) + } + } + self.channel.embeddedEventLoop.run() + } + + func testReadWhenUsingAutoreadOnChildChannel() throws { + let childChannel = NIOLockedValueBox(nil) + let readCounter = ReadCounter() + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { channel -> EventLoopFuture in + childChannel.withLockedValue { childChannel in + childChannel = channel + } + + // We're going to _enable_ autoRead on this channel. + return channel.setOption(ChannelOptions.autoRead, value: true).flatMap { + channel.pipeline.addHandler(readCounter) + } + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + XCTAssertNoThrow(try connectionSetup()) + + // Let's open a stream. + let streamID = HTTP2StreamID(1) + let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders))) + XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) + childChannel.withLockedValue { childChannel in + XCTAssertNotNil(childChannel) + } + + // There should be two calls to read: the first, when the stream was activated, the second after the HEADERS + // frame was delivered. + XCTAssertEqual(readCounter.readCount, 2) + + // Now deliver a data frame. + let dataFrame = try HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(ByteBuffer(string: "Hello, world!"))))).encode() + XCTAssertNoThrow(try self.channel.writeInbound(dataFrame)) + + // This frame should have been immediately delivered, _and_ a call to read should have happened. + XCTAssertEqual(readCounter.readCount, 3) + + // Delivering two more frames causes two more calls to read. + XCTAssertNoThrow(try self.channel.writeInbound(dataFrame)) + XCTAssertNoThrow(try self.channel.writeInbound(dataFrame)) + XCTAssertEqual(readCounter.readCount, 5) + + XCTAssertNoThrow(try self.channel.finish()) + } + + func testStreamChannelSupportsSyncOptions() throws { + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { channel in + XCTAssert(channel is HTTP2StreamChannel) + if let sync = channel.syncOptions { + do { + let streamID = try sync.getOption(HTTP2StreamChannelOptions.streamID) + XCTAssertEqual(streamID, HTTP2StreamID(1)) + + let autoRead = try sync.getOption(ChannelOptions.autoRead) + try sync.setOption(ChannelOptions.autoRead, value: !autoRead) + XCTAssertNotEqual(autoRead, try sync.getOption(ChannelOptions.autoRead)) + } catch { + XCTFail("Missing StreamID") + } + } else { + XCTFail("syncOptions was nil but should be supported for HTTP2StreamChannel") + } + + return channel.close() + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + XCTAssertNoThrow(try connectionSetup()) + + let frame = HTTP2Frame(streamID: HTTP2StreamID(1), payload: .headers(.init(headers: .basicRequestHeaders))) + XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) + } + + func testStreamErrorIsDeliveredToChannel() throws { + let goodHeaders = HPACKHeaders([ + (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost") + ]) + var badHeaders = goodHeaders + badHeaders.add(name: "transfer-encoding", value: "chunked") + + let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: self.channel.eventLoop) { channel in + return channel.eventLoop.makeSucceededFuture(()) + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + XCTAssertNoThrow(try connectionSetup(mode: .client)) + XCTAssertEqual(try self.channel.readAllBuffers().count, 3) // drain outbound magic, settings & ACK + + // We need to activate the underlying channel here. + XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 80)).wait()) + + // Now create two child channels with error recording handlers in them. Save one, ignore the other. + let errorRecorder = ErrorRecorder() + let childChannel = NIOLockedValueBox(nil) + let multiplexer = try http2Handler.multiplexer.wait() + multiplexer.createStreamChannel(promise: nil) { channel in + childChannel.withLockedValue { childChannel in + childChannel = channel + } + return channel.pipeline.addHandler(errorRecorder) + } + + let secondErrorRecorder = ErrorRecorder() + multiplexer.createStreamChannel(promise: nil) { channel in + // For this one we'll do a write immediately, to bring it into existence and give it a stream ID. + channel.writeAndFlush(HTTP2Frame.FramePayload.headers(.init(headers: goodHeaders)), promise: nil) + return channel.pipeline.addHandler(secondErrorRecorder) + } + self.channel.embeddedEventLoop.run() + + // On this child channel, write and flush an invalid headers frame. + XCTAssertEqual(errorRecorder.errors.count, 0) + XCTAssertEqual(secondErrorRecorder.errors.count, 0) + + childChannel.withLockedValue { childChannel in + childChannel!.writeAndFlush(HTTP2Frame.FramePayload.headers(.init(headers: badHeaders)), promise: nil) + } + + // It should come through to the channel. + XCTAssertEqual( + errorRecorder.errors.first.flatMap { $0 as? NIOHTTP2Errors.ForbiddenHeaderField }, + NIOHTTP2Errors.forbiddenHeaderField(name: "transfer-encoding", value: "chunked") + ) + XCTAssertEqual(secondErrorRecorder.errors.count, 0) + + // Simulate closing the child channel in response to the error. + childChannel.withLockedValue { childChannel in + childChannel!.close(promise: nil) + } + self.channel.embeddedEventLoop.run() + + // Only the HEADERS frames should have been written: we closed before the other channel became active, so + // it should not have triggered an RST_STREAM frame. + let frames = try self.channel.decodedSentFrames() + XCTAssertEqual(frames.count, 1) + + frames[0].assertHeadersFrame(endStream: false, streamID: 1, headers: goodHeaders, priority: nil, type: .request) + } + + func testPendingReadsAreFlushedEvenWithoutUnsatisfiedReadOnChannelInactive() throws { + let goodHeaders = HPACKHeaders([ + (":path", "/"), (":method", "GET"), (":scheme", "https"), (":authority", "localhost") + ]) + + let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: self.channel.eventLoop) { channel in + XCTFail("Server push is unexpected") + return channel.eventLoop.makeSucceededFuture(()) + } + XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) + XCTAssertNoThrow(try connectionSetup(mode: .client)) + XCTAssertEqual(try self.channel.readAllBuffers().count, 3) // drain outbound magic, settings & ACK + + // Now create and save a child channel with an error recording handler in it. + let consumer = ReadAndFrameConsumer() + let childChannel = NIOLockedValueBox(nil) + let multiplexer = try http2Handler.multiplexer.wait() + multiplexer.createStreamChannel(promise: nil) { channel in + childChannel.withLockedValue { childChannel in + childChannel = channel + } + return channel.pipeline.addHandler(consumer) + } + self.channel.embeddedEventLoop.run() + + let streamID = HTTP2StreamID(1) + + let payload = HTTP2Frame.FramePayload.Headers(headers: goodHeaders, endStream: true) + try childChannel.withLockedValue { childChannel in + XCTAssertNoThrow(try childChannel!.writeAndFlush(HTTP2Frame.FramePayload.headers(payload)).wait()) + } + + let frames = try self.channel.decodedSentFrames() + XCTAssertEqual(frames.count, 1) + frames.first?.assertHeadersFrameMatches(this: HTTP2Frame(streamID: streamID, payload: .headers(payload))) + + XCTAssertEqual(consumer.readCount, 1) + + // 1. pass header onwards + + let responseHeaderFrame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: [":status": "200"]))) + XCTAssertNoThrow(try self.channel.writeInbound(responseHeaderFrame.encode())) + XCTAssertEqual(consumer.receivedFrames.count, 1) + XCTAssertEqual(consumer.readCompleteCount, 1) + XCTAssertEqual(consumer.readCount, 2) + + consumer.forwardRead = false + + // 2. pass body onwards + + let responseFrame1 = HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(.init(string: "foo"))))) + XCTAssertNoThrow(try self.channel.writeInbound(responseFrame1.encode())) + XCTAssertEqual(consumer.receivedFrames.count, 2) + XCTAssertEqual(consumer.readCompleteCount, 2) + XCTAssertEqual(consumer.readCount, 3) + XCTAssertEqual(consumer.readPending, true) + + // 3. pass on more body - should not change a thing, since read is pending in consumer + + let responseFrame2 = HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(.init(string: "bar")), endStream: false))) + XCTAssertNoThrow(try self.channel.writeInbound(responseFrame2.encode())) + XCTAssertEqual(consumer.receivedFrames.count, 2) + XCTAssertEqual(consumer.readCompleteCount, 2) + XCTAssertEqual(consumer.readCount, 3) + XCTAssertEqual(consumer.readPending, true) + + // 4. signal stream is closed – this should force forward all pending frames + + let responseFrame3 = HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(.init(string: "bar")), endStream: true))) + XCTAssertNoThrow(try self.channel.writeInbound(responseFrame3.encode())) + XCTAssertEqual(consumer.receivedFrames.count, 4) + XCTAssertEqual(consumer.readCompleteCount, 3) + XCTAssertEqual(consumer.readCount, 3) + XCTAssertEqual(consumer.channelInactiveCount, 1) + XCTAssertEqual(consumer.readPending, true) + } +} + +private final class ReadAndFrameConsumer: ChannelInboundHandler, ChannelOutboundHandler { + typealias InboundIn = HTTP2Frame.FramePayload + typealias OutboundIn = HTTP2Frame.FramePayload + + private(set) var receivedFrames: [HTTP2Frame.FramePayload] = [] + private(set) var readCount = 0 + private(set) var readCompleteCount = 0 + private(set) var channelInactiveCount = 0 + private(set) var readPending = false + + var forwardRead = true { + didSet { + if self.forwardRead, self.readPending { + self.context.read() + self.readPending = false + } + } + } + + var context: ChannelHandlerContext! + + func handlerAdded(context: ChannelHandlerContext) { + self.context = context + } + + func handlerRemoved(context: ChannelHandlerContext) { + self.context = context + } + + func channelRead(context: ChannelHandlerContext, data: NIOAny) { + self.receivedFrames.append(self.unwrapInboundIn(data)) + context.fireChannelRead(data) + } + + func channelReadComplete(context: ChannelHandlerContext) { + self.readCompleteCount += 1 + context.fireChannelReadComplete() + } + + func channelInactive(context: ChannelHandlerContext) { + self.channelInactiveCount += 1 + context.fireChannelInactive() + } + + func read(context: ChannelHandlerContext) { + self.readCount += 1 + if forwardRead { + context.read() + self.readPending = false + } else { + self.readPending = true + } + } +} + +extension HTTP2Frame { + func encode() throws -> ByteBuffer { + let allocator = ByteBufferAllocator() + var buffer = allocator.buffer(capacity: 1024) + + var frameEncoder = HTTP2FrameEncoder(allocator: allocator) + let extraData = try frameEncoder.encode(frame: self, to: &buffer) + if let extraData = extraData { + switch extraData { + case .byteBuffer(let extraBuffer): + buffer.writeImmutableBuffer(extraBuffer) + default: + preconditionFailure() + } + } + return buffer + } +} diff --git a/Tests/NIOHTTP2Tests/SimpleClientServerInlineStreamMultiplexerTests+XCTest.swift b/Tests/NIOHTTP2Tests/SimpleClientServerInlineStreamMultiplexerTests+XCTest.swift new file mode 100644 index 0000000..fd350e1 --- /dev/null +++ b/Tests/NIOHTTP2Tests/SimpleClientServerInlineStreamMultiplexerTests+XCTest.swift @@ -0,0 +1,39 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// +// +// SimpleClientServerInlineStreamMultiplexerTests+XCTest.swift +// +import XCTest + +/// +/// NOTE: This file was generated by generate_linux_tests.rb +/// +/// Do NOT edit this file directly as it will be regenerated automatically when needed. +/// + +extension SimpleClientServerInlineStreamMultiplexerTests { + + @available(*, deprecated, message: "not actually deprecated. Just deprecated to allow deprecated tests (which test deprecated functionality) without warnings") + static var allTests : [(String, (SimpleClientServerInlineStreamMultiplexerTests) -> () throws -> Void)] { + return [ + ("testSendingDataFrameWithLargeFile", testSendingDataFrameWithLargeFile), + ("testAutomaticFlowControl", testAutomaticFlowControl), + ("testNoStreamWindowUpdateOnEndStreamFrameFromServer", testNoStreamWindowUpdateOnEndStreamFrameFromServer), + ("testNoStreamWindowUpdateOnEndStreamFrameFromClient", testNoStreamWindowUpdateOnEndStreamFrameFromClient), + ("testStreamCreationOrder", testStreamCreationOrder), + ("testWriteWithAlreadyCompletedPromise", testWriteWithAlreadyCompletedPromise), + ] + } +} + diff --git a/Tests/NIOHTTP2Tests/SimpleClientServerInlineStreamMultiplexerTests.swift b/Tests/NIOHTTP2Tests/SimpleClientServerInlineStreamMultiplexerTests.swift new file mode 100644 index 0000000..6a2feb5 --- /dev/null +++ b/Tests/NIOHTTP2Tests/SimpleClientServerInlineStreamMultiplexerTests.swift @@ -0,0 +1,331 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2017-2023 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import XCTest +import NIOCore +import NIOEmbedded +import NIOHPACK +@testable import NIOHTTP2 + + +class SimpleClientServerInlineStreamMultiplexerTests: XCTestCase { + var clientChannel: EmbeddedChannel! + var serverChannel: EmbeddedChannel! + + override func setUp() { + self.clientChannel = EmbeddedChannel() + self.serverChannel = EmbeddedChannel() + } + + override func tearDown() { + self.clientChannel = nil + self.serverChannel = nil + } + + static let defaultMultiplexerCallback: (@Sendable (Channel) -> EventLoopFuture) = { channel in + channel.pipeline.eventLoop.makeSucceededVoidFuture() + } + + /// Establish a basic HTTP/2 connection. + func basicHTTP2Connection(clientSettings: HTTP2Settings = nioDefaultSettings, + serverSettings: HTTP2Settings = nioDefaultSettings, + maximumBufferedControlFrames: Int = 10000, + withMultiplexerCallback multiplexerCallback: @escaping (@Sendable (Channel) -> EventLoopFuture) = defaultMultiplexerCallback) throws { + + var clientConnectionConfiguration = NIOHTTP2Handler.ConnectionConfiguration() + clientConnectionConfiguration.initialSettings = clientSettings + clientConnectionConfiguration.maximumBufferedControlFrames = maximumBufferedControlFrames + XCTAssertNoThrow(try self.clientChannel.pipeline.addHandler(NIOHTTP2Handler(mode: .client, + eventLoop: self.clientChannel.eventLoop, + connectionConfiguration: clientConnectionConfiguration, + inboundStreamInitializer: multiplexerCallback)).wait()) + var serverConnectionConfiguration = NIOHTTP2Handler.ConnectionConfiguration() + serverConnectionConfiguration.initialSettings = serverSettings + serverConnectionConfiguration.maximumBufferedControlFrames = maximumBufferedControlFrames + XCTAssertNoThrow(try self.serverChannel.pipeline.addHandler(NIOHTTP2Handler(mode: .server, + eventLoop: self.serverChannel.eventLoop, + connectionConfiguration: serverConnectionConfiguration, + inboundStreamInitializer: multiplexerCallback)).wait()) + + try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel, + clientSettings: clientSettings, serverSettings: serverSettings) + } + + func testSendingDataFrameWithLargeFile() throws { + // Begin by getting the connection up. + // We add the stream multiplexer because it'll emit WINDOW_UPDATE frames, which we need. + let serverHandler = InboundFramePayloadRecorder() + try self.basicHTTP2Connection() { channel in + return channel.pipeline.addHandler(serverHandler) + } + + // We're going to create a largish temp file: 3 data frames in size. + var bodyData = self.clientChannel.allocator.buffer(capacity: 1<<14) + for val in (0..<((1<<14) / MemoryLayout.size)) { + bodyData.writeInteger(val) + } + + try withTemporaryFile { (handle, path) in + for _ in (0..<3) { + handle.appendBuffer(bodyData) + } + + let region = try FileRegion(fileHandle: handle) + + let clientHandler = InboundFramePayloadRecorder() + let childChannelPromise = self.clientChannel.eventLoop.makePromise(of: Channel.self) + let multiplexer = try (self.clientChannel.pipeline.context(handlerType: NIOHTTP2Handler.self).wait().handler as! NIOHTTP2Handler).multiplexer.wait() + multiplexer.createStreamChannel(promise: childChannelPromise) { channel in + return channel.pipeline.addHandler(clientHandler) + } + (self.clientChannel.eventLoop as! EmbeddedEventLoop).run() + let childChannel = try childChannelPromise.futureResult.wait() + + // Start by sending the headers. + let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let reqFrame = HTTP2Frame.FramePayload.headers(.init(headers: headers)) + childChannel.writeAndFlush(reqFrame) .whenComplete { + print("Headers: \($0)") + } + self.interactInMemory(self.clientChannel, self.serverChannel) + + serverHandler.receivedFrames.assertFramePayloadsMatch([reqFrame]) + self.clientChannel.assertNoFramesReceived() + self.serverChannel.assertNoFramesReceived() + + // Ok, we're gonna send the body here. + let reqBodyFrame = HTTP2Frame.FramePayload.data(.init(data: .fileRegion(region), endStream: true)) + childChannel.writeAndFlush(reqBodyFrame) .whenComplete { + print("Data: \($0)") + } + self.interactInMemory(self.clientChannel, self.serverChannel) + + // We now expect 3 frames. + let dataFrames = (0..<3).map { idx in HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(bodyData), endStream: idx == 2)) } + serverHandler.receivedFrames.assertFramePayloadsMatch([reqFrame] + dataFrames) + + // The client will have seen a pair of window updates: one on the connection, one on the stream. + try self.clientChannel.assertReceivedFrame().assertWindowUpdateFrame(streamID: 0, windowIncrement: 32768) + clientHandler.receivedFrames.assertFramePayloadsMatch([HTTP2Frame.FramePayload.windowUpdate(windowSizeIncrement: 32768)]) + + // No frames left. + self.clientChannel.assertNoFramesReceived() + self.serverChannel.assertNoFramesReceived() + } + + XCTAssertNoThrow(try self.clientChannel.finish()) + XCTAssertNoThrow(try self.serverChannel.finish()) + } + + func testAutomaticFlowControl() throws { + // Begin by getting the connection up. + // We add the stream multiplexer here because it manages automatic flow control. + try self.basicHTTP2Connection() { channel in + return channel.eventLoop.makeSucceededFuture(()) + } + + // Now we're going to send a request, including a very large body: 65536 bytes in size. To avoid spending too much + // time initializing buffers, we're going to send the same 1kB data frame 64 times. + let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let requestBody = ByteBuffer(repeating: 0x04, count: 1024) + + // We're going to open a stream and queue up the frames for that stream. + let handler = try self.clientChannel.pipeline.context(handlerType: NIOHTTP2Handler.self).wait().handler as! NIOHTTP2Handler + let childHandler = InboundFramePayloadRecorder() + let multiplexer = try handler.multiplexer.wait() + multiplexer.createStreamChannel(promise: nil) { channel in + let reqFramePayload = HTTP2Frame.FramePayload.headers(.init(headers: headers)) + channel.write(reqFramePayload, promise: nil) + + // Now prepare the large body. + var reqBodyFramePayload = HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(requestBody))) + for _ in 0..<63 { + channel.write(reqBodyFramePayload, promise: nil) + } + reqBodyFramePayload = .data(.init(data: .byteBuffer(requestBody), endStream: true)) + channel.writeAndFlush(reqBodyFramePayload, promise: nil) + + return channel.pipeline.addHandler(childHandler) + } + (self.clientChannel.eventLoop as! EmbeddedEventLoop).run() + + // Ok, we now want to send this data to the server. + self.interactInMemory(self.clientChannel, self.serverChannel) + + // We should also see 4 window update frames on the client side: two for the stream, two for the connection. + try self.clientChannel.assertReceivedFrame().assertWindowUpdateFrame(streamID: 0, windowIncrement: 32768) + try self.clientChannel.assertReceivedFrame().assertWindowUpdateFrame(streamID: 0, windowIncrement: 32768) + + let expectedChildFrames = [HTTP2Frame.FramePayload.windowUpdate(windowSizeIncrement: 32768)] + childHandler.receivedFrames.assertFramePayloadsMatch(expectedChildFrames) + + // No other frames should be emitted, though the server may have many. + self.clientChannel.assertNoFramesReceived() + XCTAssertNoThrow(try self.clientChannel.finish()) + XCTAssertNoThrow(try self.serverChannel.finish()) + } + + func testNoStreamWindowUpdateOnEndStreamFrameFromServer() throws { + let maxFrameSize = (1 << 24) - 1 // Max value of SETTINGS_MAX_FRAME_SIZE is 2^24-1. + let clientSettings = nioDefaultSettings + [HTTP2Setting(parameter: .maxFrameSize, value: maxFrameSize)] + + // Begin by getting the connection up. + // We add the stream multiplexer here because it manages automatic flow control, and because we want the server + // to correctly confirm we don't receive a frame for the child stream. + let childHandler = InboundFramePayloadRecorder() + try self.basicHTTP2Connection(clientSettings: clientSettings) { channel in + + // Here we send a large response: 65535 bytes in size. + let responseHeaders = HPACKHeaders([(":status", "200"), ("content-length", "65535")]) + + var responseBody = self.clientChannel.allocator.buffer(capacity: 65535) + responseBody.writeBytes(Array(repeating: UInt8(0x04), count: 65535)) + + let respFramePayload = HTTP2Frame.FramePayload.headers(.init(headers: responseHeaders)) + channel.write(respFramePayload, promise: nil) + + // Now prepare the large body. + let respBodyFramePayload = HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(responseBody), endStream: true)) + channel.writeAndFlush(respBodyFramePayload, promise: nil) + return channel.pipeline.addHandler(childHandler) + } + + // Now we're going to send a small request. + let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + + // We're going to open a stream and queue up the frames for that stream. + let handler = try self.clientChannel.pipeline.handler(type: NIOHTTP2Handler.self).wait() + // We need END_STREAM set here, because that will force the stream to be closed on the response. + let reqFrame = HTTP2Frame.FramePayload.headers(.init(headers: headers, endStream: true)) + let multiplexer = try handler.multiplexer.wait() + multiplexer.createStreamChannel(promise: nil) { channel in + channel.writeAndFlush(reqFrame, promise: nil) + return channel.eventLoop.makeSucceededFuture(()) + } + self.clientChannel.embeddedEventLoop.run() + + // Ok, we now want to send this data to the server. + self.interactInMemory(self.clientChannel, self.serverChannel) + + // The server should have seen 1 window update frame for the connection only. + try self.serverChannel.assertReceivedFrame().assertWindowUpdateFrame(streamID: 0, windowIncrement: 65535) + + // And only the request frame frame for the child stream, as there was no need to open its stream window. + childHandler.receivedFrames.assertFramePayloadsMatch([reqFrame]) + + // No other frames should be emitted, though the client may have many in a child stream. + self.serverChannel.assertNoFramesReceived() + XCTAssertNoThrow(XCTAssertTrue(try self.clientChannel.finish().isClean)) + XCTAssertNoThrow(XCTAssertTrue(try self.serverChannel.finish().isClean)) + } + + func testNoStreamWindowUpdateOnEndStreamFrameFromClient() throws { + let maxFrameSize = (1 << 24) - 1 // Max value of SETTINGS_MAX_FRAME_SIZE is 2^24-1. + let serverSettings = nioDefaultSettings + [HTTP2Setting(parameter: .maxFrameSize, value: maxFrameSize)] + + // Begin by getting the connection up. + // We add the stream multiplexer here because it manages automatic flow control, and because we want the server + // to correctly confirm we don't receive a frame for the child stream. + let childHandler = FrameRecorderHandler() + try self.basicHTTP2Connection(serverSettings: serverSettings) { channel in + return channel.eventLoop.makeSucceededFuture(()) + } + + // Now we're going to send a large request: 65535 bytes in size + let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + + // We're going to open a stream and queue up the frames for that stream. + let handler = try self.clientChannel.pipeline.handler(type: NIOHTTP2Handler.self).wait() + let multiplexer = try handler.multiplexer.wait() + multiplexer.createStreamChannel(promise: nil) { channel in + let reqFrame = HTTP2Frame.FramePayload.headers(.init(headers: headers)) + channel.write(reqFrame, promise: nil) + + var requestBody = self.clientChannel.allocator.buffer(capacity: 65535) + requestBody.writeBytes(Array(repeating: UInt8(0x04), count: 65535)) + + // Now prepare the large body. We need END_STREAM set. + let reqBodyFrame = HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(requestBody), endStream: true)) + channel.writeAndFlush(reqBodyFrame, promise: nil) + + return channel.pipeline.addHandler(childHandler) + } + self.clientChannel.embeddedEventLoop.run() + + // Ok, we now want to send this data to the server. + self.interactInMemory(self.clientChannel, self.serverChannel) + + // The client should have seen a window update on the connection. + try self.clientChannel.assertReceivedFrame().assertWindowUpdateFrame(streamID: 0, windowIncrement: 65535) + + // And nothing for the child stream, as there was no need to open its stream window. + childHandler.receivedFrames.assertFramesMatch([]) + + // No other frames should be emitted, though the server may have many in a child stream. + self.clientChannel.assertNoFramesReceived() + XCTAssertNoThrow(XCTAssertTrue(try self.clientChannel.finish().isClean)) + XCTAssertNoThrow(XCTAssertTrue(try self.serverChannel.finish().isClean)) + } + + func testStreamCreationOrder() throws { + try self.basicHTTP2Connection() + let handler = try self.clientChannel.pipeline.handler(type: NIOHTTP2Handler.self).wait() + let multiplexer = try handler.multiplexer.wait() + + let streamAPromise = self.clientChannel.eventLoop.makePromise(of: Channel.self) + multiplexer.createStreamChannel(promise: streamAPromise) { channel in + return channel.eventLoop.makeSucceededFuture(()) + } + self.clientChannel.embeddedEventLoop.run() + let streamA = try assertNoThrowWithValue(try streamAPromise.futureResult.wait()) + + let streamBPromise = self.clientChannel.eventLoop.makePromise(of: Channel.self) + multiplexer.createStreamChannel(promise: streamBPromise) { channel in + return channel.eventLoop.makeSucceededFuture(()) + } + self.clientChannel.embeddedEventLoop.run() + let streamB = try assertNoThrowWithValue(try streamBPromise.futureResult.wait()) + + let headers = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) + let headersFramePayload = HTTP2Frame.FramePayload.headers(.init(headers: headers, endStream: false)) + + // Write on 'B' first. + XCTAssertNoThrow(try streamB.writeAndFlush(headersFramePayload).wait()) + XCTAssertEqual(try streamB.getOption(HTTP2StreamChannelOptions.streamID).wait(), HTTP2StreamID(1)) + + // Now write on stream 'A'. This would fail on frame-based stream channel. + XCTAssertNoThrow(try streamA.writeAndFlush(headersFramePayload).wait()) + XCTAssertEqual(try streamA.getOption(HTTP2StreamChannelOptions.streamID).wait(), HTTP2StreamID(3)) + } + + func testWriteWithAlreadyCompletedPromise() throws { + try self.basicHTTP2Connection() + let handler = try self.clientChannel.pipeline.handler(type: NIOHTTP2Handler.self).wait() + let multiplexer = try handler.multiplexer.wait() + + let streamPromise = self.clientChannel.eventLoop.makePromise(of: Channel.self) + multiplexer.createStreamChannel(promise: streamPromise) { channel in + return channel.eventLoop.makeSucceededFuture(()) + } + + self.clientChannel.embeddedEventLoop.run() + let stream = try assertNoThrowWithValue(try streamPromise.futureResult.wait()) + + let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let headerPayload = HTTP2Frame.FramePayload.headers(.init(headers: headers)) + let promise = self.clientChannel.eventLoop.makePromise(of: Void.self) + promise.succeed(()) + stream.writeAndFlush(headerPayload, promise: promise) + } +} diff --git a/Tests/NIOHTTP2Tests/TestUtilities.swift b/Tests/NIOHTTP2Tests/TestUtilities.swift index cf44e1e..909546a 100644 --- a/Tests/NIOHTTP2Tests/TestUtilities.swift +++ b/Tests/NIOHTTP2Tests/TestUtilities.swift @@ -176,6 +176,21 @@ extension EmbeddedChannel { return receivedFrames } + + /// Retrieve all sent frames. + func decodedSentFrames(file: StaticString = #filePath, line: UInt = #line) throws -> [HTTP2Frame] { + var receivedFrames: [HTTP2Frame] = Array() + + var frameDecoder = HTTP2FrameDecoder(allocator: self.allocator, expectClientMagic: false) + while let buffer = try assertNoThrowWithValue(self.readOutbound(as: ByteBuffer.self), file: (file), line: line) { + frameDecoder.append(bytes: buffer) + if let (frame, _) = try frameDecoder.nextFrame() { + receivedFrames.append(frame) + } + } + + return receivedFrames + } } extension HTTP2Frame { diff --git a/docker/docker-compose.2004.55.yaml b/docker/docker-compose.2004.55.yaml index 56cca75..0dff83f 100644 --- a/docker/docker-compose.2004.55.yaml +++ b/docker/docker-compose.2004.55.yaml @@ -29,15 +29,15 @@ services: environment: - MAX_ALLOCS_ALLOWED_1k_requests_interleaved=46200 - MAX_ALLOCS_ALLOWED_1k_requests_noninterleaved=45100 - - MAX_ALLOCS_ALLOWED_client_server_h1_request_response=302050 - - MAX_ALLOCS_ALLOWED_client_server_request_response=266050 + - MAX_ALLOCS_ALLOWED_client_server_h1_request_response=304050 + - MAX_ALLOCS_ALLOWED_client_server_request_response=268050 - MAX_ALLOCS_ALLOWED_create_client_stream_channel=40050 - MAX_ALLOCS_ALLOWED_get_100000_headers_canonical_form=200050 - MAX_ALLOCS_ALLOWED_get_100000_headers_canonical_form_trimming_whitespace=200050 - MAX_ALLOCS_ALLOWED_get_100000_headers_canonical_form_trimming_whitespace_from_long_string=300050 - MAX_ALLOCS_ALLOWED_get_100000_headers_canonical_form_trimming_whitespace_from_short_string=200050 - MAX_ALLOCS_ALLOWED_hpack_decoding=5050 - - MAX_ALLOCS_ALLOWED_stream_teardown_100_concurrent=302950 + - MAX_ALLOCS_ALLOWED_stream_teardown_100_concurrent=303050 shell: image: swift-nio-http2:20.04-5.5 diff --git a/docker/docker-compose.2004.56.yaml b/docker/docker-compose.2004.56.yaml index 0639f5c..15e68dd 100644 --- a/docker/docker-compose.2004.56.yaml +++ b/docker/docker-compose.2004.56.yaml @@ -27,15 +27,15 @@ services: environment: - MAX_ALLOCS_ALLOWED_1k_requests_interleaved=43200 - MAX_ALLOCS_ALLOWED_1k_requests_noninterleaved=42100 - - MAX_ALLOCS_ALLOWED_client_server_h1_request_response=296050 - - MAX_ALLOCS_ALLOWED_client_server_request_response=262050 + - MAX_ALLOCS_ALLOWED_client_server_h1_request_response=298050 + - MAX_ALLOCS_ALLOWED_client_server_request_response=264050 - MAX_ALLOCS_ALLOWED_create_client_stream_channel=39050 - MAX_ALLOCS_ALLOWED_get_100000_headers_canonical_form=200050 - MAX_ALLOCS_ALLOWED_get_100000_headers_canonical_form_trimming_whitespace=200050 - MAX_ALLOCS_ALLOWED_get_100000_headers_canonical_form_trimming_whitespace_from_long_string=300050 - MAX_ALLOCS_ALLOWED_get_100000_headers_canonical_form_trimming_whitespace_from_short_string=200050 - MAX_ALLOCS_ALLOWED_hpack_decoding=5050 - - MAX_ALLOCS_ALLOWED_stream_teardown_100_concurrent=292950 + - MAX_ALLOCS_ALLOWED_stream_teardown_100_concurrent=293050 shell: image: swift-nio-http2:20.04-5.6 diff --git a/docker/docker-compose.2204.57.yaml b/docker/docker-compose.2204.57.yaml index f7342d8..df4f297 100644 --- a/docker/docker-compose.2204.57.yaml +++ b/docker/docker-compose.2204.57.yaml @@ -27,15 +27,15 @@ services: environment: - MAX_ALLOCS_ALLOWED_1k_requests_interleaved=43200 - MAX_ALLOCS_ALLOWED_1k_requests_noninterleaved=42100 - - MAX_ALLOCS_ALLOWED_client_server_h1_request_response=296050 - - MAX_ALLOCS_ALLOWED_client_server_request_response=262050 + - MAX_ALLOCS_ALLOWED_client_server_h1_request_response=298050 + - MAX_ALLOCS_ALLOWED_client_server_request_response=264050 - MAX_ALLOCS_ALLOWED_create_client_stream_channel=39050 - MAX_ALLOCS_ALLOWED_get_100000_headers_canonical_form=200050 - MAX_ALLOCS_ALLOWED_get_100000_headers_canonical_form_trimming_whitespace=200050 - MAX_ALLOCS_ALLOWED_get_100000_headers_canonical_form_trimming_whitespace_from_long_string=300050 - MAX_ALLOCS_ALLOWED_get_100000_headers_canonical_form_trimming_whitespace_from_short_string=200050 - MAX_ALLOCS_ALLOWED_hpack_decoding=5050 - - MAX_ALLOCS_ALLOWED_stream_teardown_100_concurrent=292950 + - MAX_ALLOCS_ALLOWED_stream_teardown_100_concurrent=293050 shell: image: swift-nio-http2:22.04-5.7 diff --git a/docker/docker-compose.2204.58.yaml b/docker/docker-compose.2204.58.yaml index 66b0ec7..3637b58 100644 --- a/docker/docker-compose.2204.58.yaml +++ b/docker/docker-compose.2204.58.yaml @@ -26,15 +26,15 @@ services: environment: - MAX_ALLOCS_ALLOWED_1k_requests_interleaved=43200 - MAX_ALLOCS_ALLOWED_1k_requests_noninterleaved=42100 - - MAX_ALLOCS_ALLOWED_client_server_h1_request_response=296050 - - MAX_ALLOCS_ALLOWED_client_server_request_response=262050 + - MAX_ALLOCS_ALLOWED_client_server_h1_request_response=298050 + - MAX_ALLOCS_ALLOWED_client_server_request_response=264050 - MAX_ALLOCS_ALLOWED_create_client_stream_channel=39050 - MAX_ALLOCS_ALLOWED_get_100000_headers_canonical_form=200050 - MAX_ALLOCS_ALLOWED_get_100000_headers_canonical_form_trimming_whitespace=200050 - MAX_ALLOCS_ALLOWED_get_100000_headers_canonical_form_trimming_whitespace_from_long_string=300050 - MAX_ALLOCS_ALLOWED_get_100000_headers_canonical_form_trimming_whitespace_from_short_string=200050 - MAX_ALLOCS_ALLOWED_hpack_decoding=5050 - - MAX_ALLOCS_ALLOWED_stream_teardown_100_concurrent=292950 + - MAX_ALLOCS_ALLOWED_stream_teardown_100_concurrent=293050 - IMPORT_CHECK_ARG=--explicit-target-dependency-import-check error shell: diff --git a/docker/docker-compose.2204.main.yaml b/docker/docker-compose.2204.main.yaml index 2e2c36e..ef9be6d 100644 --- a/docker/docker-compose.2204.main.yaml +++ b/docker/docker-compose.2204.main.yaml @@ -26,15 +26,15 @@ services: environment: - MAX_ALLOCS_ALLOWED_1k_requests_interleaved=43200 - MAX_ALLOCS_ALLOWED_1k_requests_noninterleaved=42100 - - MAX_ALLOCS_ALLOWED_client_server_h1_request_response=296050 - - MAX_ALLOCS_ALLOWED_client_server_request_response=262050 + - MAX_ALLOCS_ALLOWED_client_server_h1_request_response=298050 + - MAX_ALLOCS_ALLOWED_client_server_request_response=264050 - MAX_ALLOCS_ALLOWED_create_client_stream_channel=39050 - MAX_ALLOCS_ALLOWED_get_100000_headers_canonical_form=200050 - MAX_ALLOCS_ALLOWED_get_100000_headers_canonical_form_trimming_whitespace=200050 - MAX_ALLOCS_ALLOWED_get_100000_headers_canonical_form_trimming_whitespace_from_long_string=300050 - MAX_ALLOCS_ALLOWED_get_100000_headers_canonical_form_trimming_whitespace_from_short_string=200050 - MAX_ALLOCS_ALLOWED_hpack_decoding=5050 - - MAX_ALLOCS_ALLOWED_stream_teardown_100_concurrent=292950 + - MAX_ALLOCS_ALLOWED_stream_teardown_100_concurrent=293050 - IMPORT_CHECK_ARG=--explicit-target-dependency-import-check error shell: