diff --git a/Sources/NIOHPACK/HPACKErrors.swift b/Sources/NIOHPACK/HPACKErrors.swift index d818c64..fd3f020 100644 --- a/Sources/NIOHPACK/HPACKErrors.swift +++ b/Sources/NIOHPACK/HPACKErrors.swift @@ -71,11 +71,10 @@ public enum NIOHPACKErrors { /// A dynamic table size update was found outside its allowed place. /// They may only be included at the start of a header block. public struct IllegalDynamicTableSizeChange : NIOHPACKError {} - /// A new header could not be added to the dynamic table. Usually /// this means the header itself is larger than the current /// dynamic table size. - public struct FailedToAddIndexedHeader : NIOHPACKError where Name.Element == UInt8, Value.Element == UInt8 { + public struct FailedToAddIndexedHeader : NIOHPACKError where Name.Element == UInt8, Value.Element == UInt8 { /// The table size required to be able to add this header to the table. public let bytesNeeded: Int diff --git a/Sources/NIOHTTP2/HTTP2ChannelHandler+InlineStreamMultiplexer.swift b/Sources/NIOHTTP2/HTTP2ChannelHandler+InlineStreamMultiplexer.swift index ce726a8..f429117 100644 --- a/Sources/NIOHTTP2/HTTP2ChannelHandler+InlineStreamMultiplexer.swift +++ b/Sources/NIOHTTP2/HTTP2ChannelHandler+InlineStreamMultiplexer.swift @@ -168,14 +168,15 @@ extension NIOHTTP2Handler { /// 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 + public struct StreamMultiplexer: Sendable { + private let inlineStreamMultiplexer: InlineStreamMultiplexer.SendableView + + private let eventLoop: EventLoop /// Cannot be created by users. - internal init(_ inlineStreamMultiplexer: InlineStreamMultiplexer) { - self.inlineStreamMultiplexer = inlineStreamMultiplexer + internal init(_ inlineStreamMultiplexer: InlineStreamMultiplexer, eventLoop: EventLoop) { + self.inlineStreamMultiplexer = InlineStreamMultiplexer.SendableView(inlineStreamMultiplexer, eventLoop: eventLoop) + self.eventLoop = eventLoop } /// Create a new `Channel` for a new stream initiated by this peer. @@ -233,26 +234,79 @@ extension NIOHTTP2Handler { /// You can open a stream by calling ``openStream(_:)``. Locally-initiated stream channel objects are initialized upon creation using the supplied `initializer` which returns a type /// `Output`. This type may be `HTTP2Frame` or changed to any other type. @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) - public struct AsyncStreamMultiplexer { - @usableFromInline internal let inlineStreamMultiplexer: InlineStreamMultiplexer + public struct AsyncStreamMultiplexer: Sendable { + @usableFromInline internal let _inlineStreamMultiplexer: InlineStreamMultiplexer.SendableView public let inbound: NIOHTTP2AsyncSequence // Cannot be created by users. @usableFromInline - internal init(_ inlineStreamMultiplexer: InlineStreamMultiplexer, continuation: any AnyContinuation, inboundStreamChannels: NIOHTTP2AsyncSequence) { - self.inlineStreamMultiplexer = inlineStreamMultiplexer - self.inlineStreamMultiplexer.setChannelContinuation(continuation) + internal init(_ inlineStreamMultiplexer: InlineStreamMultiplexer, eventLoop: EventLoop, continuation: any AnyContinuation, inboundStreamChannels: NIOHTTP2AsyncSequence) { + self._inlineStreamMultiplexer = InlineStreamMultiplexer.SendableView(inlineStreamMultiplexer, eventLoop: eventLoop) + self._inlineStreamMultiplexer.setChannelContinuation(continuation) self.inbound = inboundStreamChannels } - - /// Create a stream channel initialized with the provided closure /// - Parameter initializer: A closure that will be called upon the created stream which is responsible for /// initializing the stream's `Channel`. /// - Returns: The result of the `initializer`. @inlinable public func openStream(_ initializer: @escaping NIOChannelInitializerWithOutput) async throws -> Output { - return try await self.inlineStreamMultiplexer.createStreamChannel(initializer).get() + return try await self._inlineStreamMultiplexer.createStreamChannel(initializer).get() + } + } +} + +extension InlineStreamMultiplexer { + /// InlineStreamMultiplexer.SendableView exposes only the thread-safe API of InlineStreamMultiplexer + /// + /// We use unchecked Sendable here because we unconditionally hop so we are on the right event loop + /// from here on. + @usableFromInline + internal struct SendableView: @unchecked Sendable { + @usableFromInline internal let _inlineStreamMultiplexer: InlineStreamMultiplexer + @usableFromInline internal let _eventLoop: EventLoop + + init(_ inlineStreamMultiplexer: InlineStreamMultiplexer, eventLoop: EventLoop) { + self._inlineStreamMultiplexer = inlineStreamMultiplexer + self._eventLoop = eventLoop + } + + internal func createStreamChannel(promise: EventLoopPromise?, _ streamStateInitializer: @escaping NIOHTTP2Handler.StreamInitializer) { + // Always create streams channels on the next event loop tick. This avoids re-entrancy + // issues where handlers interposed between the two HTTP/2 handlers could create streams + // in channel active which become activated twice. + self._eventLoop.execute { + self._inlineStreamMultiplexer.createStreamChannel(promise: promise, streamStateInitializer) + } + } + + internal func createStreamChannel(_ initializer: @escaping NIOChannelInitializer) -> EventLoopFuture { + // Always create streams channels on the next event loop tick. This avoids re-entrancy + // issues where handlers interposed between the two HTTP/2 handlers could create streams + // in channel active which become activated twice. + return self._eventLoop.flatSubmit { + self._inlineStreamMultiplexer.createStreamChannel(initializer) + } + } + + @inlinable + internal func createStreamChannel(_ initializer: @escaping NIOChannelInitializerWithOutput) -> EventLoopFuture { + // Always create streams channels on the next event loop tick. This avoids re-entrancy + // issues where handlers interposed between the two HTTP/2 handlers could create streams + // in channel active which become activated twice. + return self._eventLoop.flatSubmit { + self._inlineStreamMultiplexer.createStreamChannel(initializer) + } + } + + internal func setChannelContinuation(_ streamChannels: any AnyContinuation) { + if self._eventLoop.inEventLoop { + return self._inlineStreamMultiplexer.setChannelContinuation(streamChannels) + } else { + self._eventLoop.execute { + return self._inlineStreamMultiplexer.setChannelContinuation(streamChannels) + } + } } } } diff --git a/Sources/NIOHTTP2/HTTP2ChannelHandler.swift b/Sources/NIOHTTP2/HTTP2ChannelHandler.swift index fd80931..fab1ae3 100644 --- a/Sources/NIOHTTP2/HTTP2ChannelHandler.swift +++ b/Sources/NIOHTTP2/HTTP2ChannelHandler.swift @@ -177,7 +177,7 @@ public final class NIOHTTP2Handler: ChannelDuplexHandler { } /// The mode for this parser to operate in: client or server. - public enum ParserMode { + public enum ParserMode: Sendable { /// Client mode case client @@ -885,9 +885,9 @@ extension NIOHTTP2Handler { // Don't allow infinite recursion through this method. return } - + self.isUnbufferingAndFlushingAutomaticFrames = true - + loop: while true { switch self.outboundBuffer.nextFlushedWritableFrame(channelWritable: self.channelWritable) { case .noFrame: @@ -898,7 +898,7 @@ extension NIOHTTP2Handler { self.processOutboundFrame(context: context, frame: frame, promise: promise) } } - + self.isUnbufferingAndFlushingAutomaticFrames = false self.flushIfNecessary(context: context) } @@ -1163,8 +1163,9 @@ extension NIOHTTP2Handler { return try self.syncMultiplexer() } } else { + let unsafeSelf = UnsafeTransfer(self) return self._eventLoop!.submit { - return try self.syncMultiplexer() + return try unsafeSelf.wrappedValue.syncMultiplexer() } } } @@ -1176,11 +1177,14 @@ extension NIOHTTP2Handler { /// > - The caller is already on the correct event loop. public func syncMultiplexer() throws -> StreamMultiplexer { self._eventLoop!.preconditionInEventLoop() + guard let inboundStreamMultiplexer = self.inboundStreamMultiplexer else { + throw NIOHTTP2Errors.missingMultiplexer() + } - switch self.inboundStreamMultiplexer { - case let .some(.inline(multiplexer)): - return StreamMultiplexer(multiplexer) - case .some(.legacy), .none: + switch inboundStreamMultiplexer { + case let .inline(multiplexer): + return StreamMultiplexer(multiplexer, eventLoop: self._eventLoop!) + case .legacy: throw NIOHTTP2Errors.missingMultiplexer() } } @@ -1189,11 +1193,14 @@ extension NIOHTTP2Handler { @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) internal func syncAsyncStreamMultiplexer(continuation: any AnyContinuation, inboundStreamChannels: NIOHTTP2AsyncSequence) throws -> AsyncStreamMultiplexer { self._eventLoop!.preconditionInEventLoop() + guard let inboundStreamMultiplexer = self.inboundStreamMultiplexer else { + throw NIOHTTP2Errors.missingMultiplexer() + } - switch self.inboundStreamMultiplexer { - case let .some(.inline(multiplexer)): - return AsyncStreamMultiplexer(multiplexer, continuation: continuation, inboundStreamChannels: inboundStreamChannels) - case .some(.legacy), .none: + switch inboundStreamMultiplexer { + case let .inline(multiplexer): + return AsyncStreamMultiplexer(multiplexer, eventLoop: self._eventLoop!, continuation: continuation, inboundStreamChannels: inboundStreamChannels) + case .legacy: throw NIOHTTP2Errors.missingMultiplexer() } } diff --git a/Sources/NIOHTTP2/HTTP2CommonInboundStreamMultiplexer.swift b/Sources/NIOHTTP2/HTTP2CommonInboundStreamMultiplexer.swift index f3dd0df..24d70f4 100644 --- a/Sources/NIOHTTP2/HTTP2CommonInboundStreamMultiplexer.swift +++ b/Sources/NIOHTTP2/HTTP2CommonInboundStreamMultiplexer.swift @@ -113,7 +113,7 @@ extension HTTP2CommonInboundStreamMultiplexer { // If we have an async sequence of inbound stream channels yield the channel to it // but only once we are sure initialization and activation succeed if let streamChannelContinuation = self.streamChannelContinuation { - let promise = self._channel.eventLoop.makePromise(of: Any.self) + let promise = self._channel.eventLoop.makePromise(of: (any Sendable).self) promise.futureResult.whenSuccess { value in streamChannelContinuation.yield(any: value) } @@ -295,9 +295,9 @@ extension HTTP2CommonInboundStreamMultiplexer { extension HTTP2CommonInboundStreamMultiplexer { @inlinable - internal func _createStreamChannel( - _ multiplexer: HTTP2StreamChannel.OutboundStreamMultiplexer, - _ promise: EventLoopPromise?, + internal func createStreamChannel( + multiplexer: HTTP2StreamChannel.OutboundStreamMultiplexer, + promise: EventLoopPromise?, _ streamStateInitializer: @escaping NIOChannelInitializerWithOutput ) { self._channel.eventLoop.assertInEventLoop() @@ -318,9 +318,9 @@ extension HTTP2CommonInboundStreamMultiplexer { streamStateInitializer(channel).map { return $0 } } - let anyPromise: EventLoopPromise? + let anyPromise: EventLoopPromise<(any Sendable)>? if let promise = promise { - anyPromise = channel.baseChannel.eventLoop.makePromise(of: Any.self) + anyPromise = channel.baseChannel.eventLoop.makePromise(of: (any Sendable).self) anyPromise?.futureResult.whenComplete { result in switch result { case .success(let any): @@ -338,20 +338,6 @@ extension HTTP2CommonInboundStreamMultiplexer { channel.configure(initializer: anyInitializer, userPromise: anyPromise) } - @inlinable - internal func createStreamChannel( - multiplexer: HTTP2StreamChannel.OutboundStreamMultiplexer, - promise: EventLoopPromise?, - _ streamStateInitializer: @escaping NIOChannelInitializerWithOutput - ) { - // Always create streams channels on the next event loop tick. This avoids re-entrancy - // issues where handlers interposed between the two HTTP/2 handlers could create streams - // in channel active which become activated twice. - self._channel.eventLoop.execute { - self._createStreamChannel(multiplexer, promise, streamStateInitializer) - } - } - @inlinable internal func createStreamChannel( multiplexer: HTTP2StreamChannel.OutboundStreamMultiplexer, @@ -362,11 +348,13 @@ extension HTTP2CommonInboundStreamMultiplexer { return promise.futureResult } - internal func _createStreamChannel( - _ multiplexer: HTTP2StreamChannel.OutboundStreamMultiplexer, - _ promise: EventLoopPromise?, + internal func createStreamChannel( + multiplexer: HTTP2StreamChannel.OutboundStreamMultiplexer, + promise: EventLoopPromise?, _ streamStateInitializer: @escaping NIOChannelInitializer ) { + self._channel.eventLoop.assertInEventLoop() + let channel = MultiplexerAbstractChannel( allocator: self._channel.allocator, parent: self._channel, @@ -382,19 +370,6 @@ extension HTTP2CommonInboundStreamMultiplexer { channel.configure(initializer: streamStateInitializer, userPromise: promise) } - internal func createStreamChannel( - multiplexer: HTTP2StreamChannel.OutboundStreamMultiplexer, - promise: EventLoopPromise?, - _ streamStateInitializer: @escaping NIOChannelInitializer - ) { - // Always create streams channels on the next event loop tick. This avoids re-entrancy - // issues where handlers interposed between the two HTTP/2 handlers could create streams - // in channel active which become activated twice. - self._channel.eventLoop.execute { - self._createStreamChannel(multiplexer, promise, streamStateInitializer) - } - } - internal func createStreamChannel( multiplexer: HTTP2StreamChannel.OutboundStreamMultiplexer, _ streamStateInitializer: @escaping NIOChannelInitializer) -> EventLoopFuture { @@ -407,23 +382,23 @@ extension HTTP2CommonInboundStreamMultiplexer { internal func createStreamChannel( multiplexer: HTTP2StreamChannel.OutboundStreamMultiplexer, promise: EventLoopPromise?, - _ streamStateInitializer: @escaping (Channel, HTTP2StreamID) -> EventLoopFuture + _ streamStateInitializer: @escaping NIOChannelInitializerWithStreamID ) { - 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) - } + self._channel.eventLoop.assertInEventLoop() + + 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) } } @@ -454,7 +429,7 @@ extension HTTP2CommonInboundStreamMultiplexer { /// This is useful in in the case of the `HTTP2ChannelHandler` which must deal with types which hold stream initializers /// which have a generic return type. @usableFromInline -internal protocol AnyContinuation { +internal protocol AnyContinuation: Sendable { func yield(any: Any) func finish() func finish(throwing error: Error) @@ -464,7 +439,7 @@ internal protocol AnyContinuation { /// `NIOHTTP2AsyncSequence` is an implementation of the `AsyncSequence` protocol which allows iteration over a generic /// element type `Output`. @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) -public struct NIOHTTP2AsyncSequence: AsyncSequence { +public struct NIOHTTP2AsyncSequence: AsyncSequence { public struct AsyncIterator: AsyncIteratorProtocol { public typealias Element = Output diff --git a/Sources/NIOHTTP2/HTTP2Error.swift b/Sources/NIOHTTP2/HTTP2Error.swift index ae5623b..c32c43f 100644 --- a/Sources/NIOHTTP2/HTTP2Error.swift +++ b/Sources/NIOHTTP2/HTTP2Error.swift @@ -463,7 +463,9 @@ public enum NIOHTTP2Errors { /// An attempt was made to change the flow control window size, either via /// `SETTINGS` or `WINDOW_UPDATE`, but this change would move the flow control /// window size out of bounds. - public struct InvalidFlowControlWindowSize: NIOHTTP2Error, CustomStringConvertible { + public struct InvalidFlowControlWindowSize: NIOHTTP2Error, CustomStringConvertible, @unchecked Sendable { + // @unchecked Sendable because access is controlled by getters and copy-on-write setters giving this value semantics + private var storage: Storage private mutating func copyStorageIfNotUniquelyReferenced() { @@ -841,7 +843,9 @@ public enum NIOHTTP2Errors { } /// An attempt was made to use a currently unsupported feature. - public struct Unsupported: NIOHTTP2Error, CustomStringConvertible { + public struct Unsupported: NIOHTTP2Error, CustomStringConvertible, @unchecked Sendable { + // @unchecked Sendable because access is controlled by getters and copy-on-write setters giving this value semantics + private var storage: StringAndLocationStorage private mutating func copyStorageIfNotUniquelyReferenced() { @@ -933,7 +937,9 @@ public enum NIOHTTP2Errors { } /// A pseudo-header field is missing. - public struct MissingPseudoHeader: NIOHTTP2Error, CustomStringConvertible { + public struct MissingPseudoHeader: NIOHTTP2Error, CustomStringConvertible, @unchecked Sendable { + // @unchecked Sendable because access is controlled by getters and copy-on-write setters giving this value semantics + private var storage: StringAndLocationStorage private mutating func copyStorageIfNotUniquelyReferenced() { @@ -975,7 +981,9 @@ public enum NIOHTTP2Errors { } /// A pseudo-header field has been duplicated. - public struct DuplicatePseudoHeader: NIOHTTP2Error, CustomStringConvertible { + public struct DuplicatePseudoHeader: NIOHTTP2Error, CustomStringConvertible, @unchecked Sendable { + // @unchecked Sendable because access is controlled by getters and copy-on-write setters giving this value semantics + private var storage: StringAndLocationStorage private mutating func copyStorageIfNotUniquelyReferenced() { @@ -1017,7 +1025,8 @@ public enum NIOHTTP2Errors { } /// A header block contained a pseudo-header after a regular header. - public struct PseudoHeaderAfterRegularHeader: NIOHTTP2Error, CustomStringConvertible { + public struct PseudoHeaderAfterRegularHeader: NIOHTTP2Error, CustomStringConvertible, @unchecked Sendable { + private var storage: StringAndLocationStorage private mutating func copyStorageIfNotUniquelyReferenced() { @@ -1059,7 +1068,9 @@ public enum NIOHTTP2Errors { } /// An unknown pseudo-header was received. - public struct UnknownPseudoHeader: NIOHTTP2Error, CustomStringConvertible { + public struct UnknownPseudoHeader: NIOHTTP2Error, CustomStringConvertible, @unchecked Sendable { + // @unchecked Sendable because access is controlled by getters and copy-on-write setters giving this value semantics + private var storage: StringAndLocationStorage private mutating func copyStorageIfNotUniquelyReferenced() { @@ -1199,7 +1210,9 @@ public enum NIOHTTP2Errors { } /// A `:status` header was received with an invalid value. - public struct InvalidStatusValue: NIOHTTP2Error, CustomStringConvertible { + public struct InvalidStatusValue: NIOHTTP2Error, CustomStringConvertible, @unchecked Sendable { + // @unchecked Sendable because access is controlled by getters and copy-on-write setters giving this value semantics + private var storage: StringAndLocationStorage private mutating func copyStorageIfNotUniquelyReferenced() { @@ -1287,7 +1300,9 @@ public enum NIOHTTP2Errors { } /// An attempt was made to send a header field with a field name that is not valid in HTTP/2. - public struct InvalidHTTP2HeaderFieldName: NIOHTTP2Error, CustomStringConvertible { + public struct InvalidHTTP2HeaderFieldName: NIOHTTP2Error, CustomStringConvertible, @unchecked Sendable { + // @unchecked Sendable because access is controlled by getters and copy-on-write setters giving this value semantics + private var storage: StringAndLocationStorage private mutating func copyStorageIfNotUniquelyReferenced() { @@ -1330,7 +1345,9 @@ public enum NIOHTTP2Errors { /// Connection-specific header fields are forbidden in HTTP/2: this error is raised when one is /// sent or received. - public struct ForbiddenHeaderField: NIOHTTP2Error, CustomStringConvertible { + public struct ForbiddenHeaderField: NIOHTTP2Error, CustomStringConvertible, @unchecked Sendable { + // @unchecked Sendable because access is controlled by getters and copy-on-write setters giving this value semantics + private var storage: Storage private mutating func copyStorageIfNotUniquelyReferenced() { @@ -1576,7 +1593,9 @@ public enum NIOHTTP2Errors { /// As they are a wrapper error, they carry a "real" error in ``baseError``. Additionally, they cannot /// meaningfully be `Equatable`, so they aren't. There's also no additional location information: that's /// provided by the base error. - public struct StreamError: Error { + public struct StreamError: Error, @unchecked Sendable { + // @unchecked Sendable because access is controlled by getters and copy-on-write setters giving this value semantics + private final class Storage { var streamID: HTTP2StreamID var baseError: Error diff --git a/Sources/NIOHTTP2/HTTP2PipelineHelpers.swift b/Sources/NIOHTTP2/HTTP2PipelineHelpers.swift index 0cbbce4..b2abab0 100644 --- a/Sources/NIOHTTP2/HTTP2PipelineHelpers.swift +++ b/Sources/NIOHTTP2/HTTP2PipelineHelpers.swift @@ -33,6 +33,8 @@ import NIOTLS /// Configuring for servers is very similar. public let NIOHTTP2SupportedALPNProtocols = ["h2", "http/1.1"] +/// Legacy type of NIO Channel initializer callbacks which take `HTTP2StreamID` as a parameter. +public typealias NIOChannelInitializerWithStreamID = @Sendable (Channel, HTTP2StreamID) -> EventLoopFuture /// The type of NIO Channel initializer callbacks which do not need to return data. public typealias NIOChannelInitializer = @Sendable (Channel) -> EventLoopFuture /// The type of NIO Channel initializer callbacks which need to return data. @@ -105,10 +107,10 @@ extension Channel { public func configureHTTP2Pipeline(mode: NIOHTTP2Handler.ParserMode, initialLocalSettings: [HTTP2Setting] = nioDefaultSettings, position: ChannelPipeline.Position = .last, - inboundStreamStateInitializer: ((Channel, HTTP2StreamID) -> EventLoopFuture)? = nil) -> EventLoopFuture { + inboundStreamStateInitializer: NIOChannelInitializerWithStreamID? = nil) -> EventLoopFuture { return self.configureHTTP2Pipeline(mode: mode, initialLocalSettings: initialLocalSettings, position: position, targetWindowSize: 65535, inboundStreamStateInitializer: inboundStreamStateInitializer) } - + /// Configures a `ChannelPipeline` to speak HTTP/2. /// /// In general this is not entirely useful by itself, as HTTP/2 is a negotiated protocol. This helper does not handle negotiation. @@ -129,14 +131,13 @@ extension Channel { initialLocalSettings: [HTTP2Setting] = nioDefaultSettings, position: ChannelPipeline.Position = .last, targetWindowSize: Int, - inboundStreamStateInitializer: ((Channel, HTTP2StreamID) -> EventLoopFuture)? = nil) -> EventLoopFuture { + inboundStreamStateInitializer: NIOChannelInitializerWithStreamID? = nil) -> EventLoopFuture { var handlers = [ChannelHandler]() handlers.reserveCapacity(2) // Update this if we need to add more handlers, to avoid unnecessary reallocation. handlers.append(NIOHTTP2Handler(mode: mode, initialSettings: initialLocalSettings)) - let multiplexer = HTTP2StreamMultiplexer(mode: mode, channel: self, targetWindowSize: targetWindowSize, inboundStreamStateInitializer: inboundStreamStateInitializer) - handlers.append(multiplexer) + handlers.append(HTTP2StreamMultiplexer(mode: mode, channel: self, targetWindowSize: targetWindowSize, inboundStreamStateInitializer: inboundStreamStateInitializer)) - return self.pipeline.addHandlers(handlers, position: position).map { multiplexer } + return self.pipeline.addHandlers(handlers, position: position).flatMap { self.pipeline.handler(type: HTTP2StreamMultiplexer.self) } } /// Configures a `ChannelPipeline` to speak HTTP/2. @@ -158,14 +159,31 @@ extension Channel { initialLocalSettings: [HTTP2Setting] = nioDefaultSettings, position: ChannelPipeline.Position = .last, targetWindowSize: Int = 65535, - inboundStreamInitializer: ((Channel) -> EventLoopFuture)?) -> EventLoopFuture { - var handlers = [ChannelHandler]() - handlers.reserveCapacity(2) // Update this if we need to add more handlers, to avoid unnecessary reallocation. - handlers.append(NIOHTTP2Handler(mode: mode, initialSettings: initialLocalSettings)) - let multiplexer = HTTP2StreamMultiplexer(mode: mode, channel: self, targetWindowSize: targetWindowSize, inboundStreamInitializer: inboundStreamInitializer) - handlers.append(multiplexer) + inboundStreamInitializer: NIOChannelInitializer?) -> EventLoopFuture { - return self.pipeline.addHandlers(handlers, position: position).map { multiplexer } + if self.eventLoop.inEventLoop { + return self.eventLoop.makeCompletedFuture { + try self.pipeline.syncOperations.configureHTTP2Pipeline( + mode: mode, + channel: self, + initialLocalSettings: initialLocalSettings, + position: position, + targetWindowSize: targetWindowSize, + inboundStreamInitializer: inboundStreamInitializer + ) + } + } else { + return self.eventLoop.submit { + try self.pipeline.syncOperations.configureHTTP2Pipeline( + mode: mode, + channel: self, + initialLocalSettings: initialLocalSettings, + position: position, + targetWindowSize: targetWindowSize, + inboundStreamInitializer: inboundStreamInitializer + ) + } + } } /// Configures a `ChannelPipeline` to speak HTTP/2. @@ -239,8 +257,8 @@ extension Channel { /// negotiated, or if no protocol was negotiated. Must return a future that completes when the /// channel has been fully mutated. /// - Returns: An `EventLoopFuture` that completes when the channel is ready to negotiate. - public func configureHTTP2SecureUpgrade(h2ChannelConfigurator: @escaping (Channel) -> EventLoopFuture, - http1ChannelConfigurator: @escaping (Channel) -> EventLoopFuture) -> EventLoopFuture { + public func configureHTTP2SecureUpgrade(h2ChannelConfigurator: @escaping NIOChannelInitializer, + http1ChannelConfigurator: @escaping NIOChannelInitializer) -> EventLoopFuture { let alpnHandler = ApplicationProtocolNegotiationHandler { result in switch result { case .negotiated("h2"): @@ -276,12 +294,12 @@ extension Channel { /// that completes when the channel has been fully mutated. /// - Returns: `EventLoopFuture` that completes when the channel is ready. public func configureCommonHTTPServerPipeline( - h2ConnectionChannelConfigurator: ((Channel) -> EventLoopFuture)? = nil, - _ configurator: @escaping (Channel) -> EventLoopFuture + h2ConnectionChannelConfigurator: NIOChannelInitializer? = nil, + _ configurator: @escaping NIOChannelInitializer ) -> EventLoopFuture { return self.configureCommonHTTPServerPipeline(h2ConnectionChannelConfigurator: h2ConnectionChannelConfigurator, targetWindowSize: 65535, configurator) } - + /// Configures a `ChannelPipeline` to speak either HTTP/1.1 or HTTP/2 according to what can be negotiated with the client. /// /// This helper takes care of configuring the server pipeline such that it negotiates whether to @@ -300,9 +318,9 @@ extension Channel { /// that completes when the channel has been fully mutated. /// - Returns: `EventLoopFuture` that completes when the channel is ready. public func configureCommonHTTPServerPipeline( - h2ConnectionChannelConfigurator: ((Channel) -> EventLoopFuture)? = nil, + h2ConnectionChannelConfigurator: NIOChannelInitializer? = nil, targetWindowSize: Int, - _ configurator: @escaping (Channel) -> EventLoopFuture + _ configurator: @escaping NIOChannelInitializer ) -> EventLoopFuture { return self._commonHTTPServerPipeline(configurator: configurator, h2ConnectionChannelConfigurator: h2ConnectionChannelConfigurator) { channel in channel.configureHTTP2Pipeline(mode: .server, targetWindowSize: targetWindowSize) { streamChannel -> EventLoopFuture in @@ -337,7 +355,7 @@ extension Channel { connectionConfiguration: NIOHTTP2Handler.ConnectionConfiguration, streamConfiguration: NIOHTTP2Handler.StreamConfiguration, streamDelegate: NIOHTTP2StreamDelegate? = nil, - h2ConnectionChannelConfigurator: ((Channel) -> EventLoopFuture)? = nil, + h2ConnectionChannelConfigurator: NIOChannelInitializer? = nil, configurator: @escaping NIOChannelInitializer ) -> EventLoopFuture { return self._commonHTTPServerPipeline(configurator: configurator, h2ConnectionChannelConfigurator: h2ConnectionChannelConfigurator) { channel in @@ -355,11 +373,11 @@ extension Channel { } private func _commonHTTPServerPipeline( - configurator: @escaping (Channel) -> EventLoopFuture, - h2ConnectionChannelConfigurator: ((Channel) -> EventLoopFuture)?, - configureHTTP2Pipeline: @escaping (Channel) -> EventLoopFuture + configurator: @escaping NIOChannelInitializer, + h2ConnectionChannelConfigurator: NIOChannelInitializer?, + configureHTTP2Pipeline: @escaping NIOChannelInitializer ) -> EventLoopFuture { - let h2ChannelConfigurator = { (channel: Channel) -> EventLoopFuture in + let h2ChannelConfigurator: NIOChannelInitializer = { channel in configureHTTP2Pipeline(channel).flatMap { _ in if let h2ConnectionChannelConfigurator = h2ConnectionChannelConfigurator { return h2ConnectionChannelConfigurator(channel) @@ -368,7 +386,7 @@ extension Channel { } } } - let http1ChannelConfigurator = { (channel: Channel) -> EventLoopFuture in + let http1ChannelConfigurator: NIOChannelInitializer = { channel in channel.pipeline.configureHTTPServerPipeline().flatMap { _ in configurator(channel) } @@ -416,6 +434,37 @@ extension ChannelPipeline.SynchronousOperations { // `multiplexer` will always be non-nil when we are initializing with an `inboundStreamInitializer` return try handler.syncMultiplexer() } + + /// Synchronously configures a `ChannelPipeline` to speak HTTP/2. + /// + /// In general this is not entirely useful by itself, as HTTP/2 is a negotiated protocol. This helper does not handle negotiation. + /// Instead, this simply adds the handlers required to speak HTTP/2 after negotiation has completed, or when agreed by prior knowledge. + /// Whenever possible use this function to setup a HTTP/2 server pipeline, as it allows that pipeline to evolve without breaking your code. + /// + /// - Parameters: + /// - mode: The mode this pipeline will operate in, server or client. + /// - channel: to which the created``HTTP2StreamMultiplexer`` will belong. + /// - initialLocalSettings: The settings that will be used when establishing the connection. These will be sent to the peer as part of the + /// handshake. + /// - position: The position in the pipeline into which to insert these handlers. + /// - targetWindowSize: The target size of the HTTP/2 flow control window. + /// - inboundStreamInitializer: A closure that will be called whenever the remote peer initiates a new stream. This should almost always + /// be provided, especially on servers. + /// - Returns: An `EventLoopFuture` containing the `HTTP2StreamMultiplexer` inserted into this pipeline, which can be used to initiate new streams. + internal func configureHTTP2Pipeline(mode: NIOHTTP2Handler.ParserMode, + channel: Channel, + initialLocalSettings: [HTTP2Setting] = nioDefaultSettings, + position: ChannelPipeline.Position = .last, + targetWindowSize: Int = 65535, + inboundStreamInitializer: NIOChannelInitializer?) throws -> HTTP2StreamMultiplexer { + + let http2Handler = NIOHTTP2Handler(mode: mode, initialSettings: initialLocalSettings) + let multiplexer = HTTP2StreamMultiplexer(mode: mode, channel: channel, targetWindowSize: targetWindowSize, inboundStreamInitializer: inboundStreamInitializer) + try self.addHandler(http2Handler, position: position) + try self.addHandler(multiplexer, position: .after(http2Handler)) + + return multiplexer + } } // MARK: Async configurations @@ -491,6 +540,7 @@ extension Channel { internal func configureHTTP2AsyncSecureUpgrade( http1ConnectionInitializer: @escaping NIOChannelInitializerWithOutput, http2ConnectionInitializer: @escaping NIOChannelInitializerWithOutput + ) -> EventLoopFuture>> { let alpnHandler = NIOTypedApplicationProtocolNegotiationHandler>() { result in switch result { @@ -509,8 +559,10 @@ extension Channel { return self.pipeline .addHandler(alpnHandler) - .map { _ in - alpnHandler.protocolNegotiationResult + .flatMap { _ in + self.pipeline.handler(type: NIOTypedApplicationProtocolNegotiationHandler>.self).map { alpnHandler in + alpnHandler.protocolNegotiationResult + } } } @@ -610,7 +662,7 @@ extension ChannelPipeline.SynchronousOperations { } /// `NIONegotiatedHTTPVersion` is a generic negotiation result holder for HTTP/1.1 and HTTP/2 -public enum NIONegotiatedHTTPVersion { +public enum NIONegotiatedHTTPVersion: Sendable { /// Protocol negotiation resulted in the connection using HTTP/1.1. case http1_1(HTTP1Output) /// Protocol negotiation resulted in the connection using HTTP/2. diff --git a/Sources/NIOHTTP2/HTTP2StreamChannel.swift b/Sources/NIOHTTP2/HTTP2StreamChannel.swift index d00a135..9bafca4 100644 --- a/Sources/NIOHTTP2/HTTP2StreamChannel.swift +++ b/Sources/NIOHTTP2/HTTP2StreamChannel.swift @@ -146,7 +146,9 @@ private enum HTTP2StreamData { } @usableFromInline -final class HTTP2StreamChannel: Channel, ChannelCore { +final class HTTP2StreamChannel: Channel, ChannelCore, @unchecked Sendable { + // @unchecked Sendable because the only mutable state is `_pipeline` which is only modified in init + /// The stream data type of the channel. private let streamDataType: HTTP2StreamDataType @@ -181,7 +183,7 @@ final class HTTP2StreamChannel: Channel, ChannelCore { self._pipeline = ChannelPipeline(channel: self) } - internal func configure(initializer: ((Channel, HTTP2StreamID) -> EventLoopFuture)?, userPromise promise: EventLoopPromise?) { + internal func configure(initializer: NIOChannelInitializerWithStreamID?, userPromise promise: EventLoopPromise?) { assert(self.streamDataType == .frame) // We need to configure this channel. This involves doing four things: // 1. Setting our autoRead state from the parent @@ -207,7 +209,7 @@ final class HTTP2StreamChannel: Channel, ChannelCore { } } - internal func configure(initializer: ((Channel) -> EventLoopFuture)?, userPromise promise: EventLoopPromise?) { + internal func configure(initializer: NIOChannelInitializer?, userPromise promise: EventLoopPromise?) { assert(self.streamDataType == .framePayload) // We need to configure this channel. This involves doing four things: // 1. Setting our autoRead state from the parent @@ -234,7 +236,7 @@ final class HTTP2StreamChannel: Channel, ChannelCore { // This variant is used in the async stream case. // It uses `Any`s because when called from `configureInboundStream` it is passed the initializer stored on the handler // which can't be a typed generic without changing the handler API. - internal func configure(initializer: (@escaping (Channel) -> EventLoopFuture), userPromise promise: EventLoopPromise?) { + internal func configure(initializer: @escaping NIOChannelInitializerWithOutput, userPromise promise: EventLoopPromise?) { assert(self.streamDataType == .framePayload) // We need to configure this channel. This involves doing four things: // 1. Setting our autoRead state from the parent @@ -265,7 +267,7 @@ final class HTTP2StreamChannel: Channel, ChannelCore { /// Gets the 'autoRead' option from the parent channel and invokes the `body` closure with the /// result. This may be done synchronously if the parent `Channel` supports synchronous options. - private func getAutoReadFromParent(_ body: @escaping (Result) -> Void) { + private func getAutoReadFromParent(_ body: @Sendable @escaping (Result) -> Void) { // This force unwrap is safe as parent is assigned in the initializer, and never unassigned. // Note we also don't set the value here: the additional `map` causes an extra allocation // when using a Swift 5.0 compiler. diff --git a/Sources/NIOHTTP2/HTTP2StreamDelegate.swift b/Sources/NIOHTTP2/HTTP2StreamDelegate.swift index 4125449..e348fa4 100644 --- a/Sources/NIOHTTP2/HTTP2StreamDelegate.swift +++ b/Sources/NIOHTTP2/HTTP2StreamDelegate.swift @@ -17,7 +17,7 @@ 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 { +public protocol NIOHTTP2StreamDelegate: Sendable { /// A new HTTP/2 stream was created with the given ID. func streamCreated(_ id: HTTP2StreamID, channel: Channel) diff --git a/Sources/NIOHTTP2/HTTP2StreamMultiplexer.swift b/Sources/NIOHTTP2/HTTP2StreamMultiplexer.swift index e22b0a8..ef24442 100644 --- a/Sources/NIOHTTP2/HTTP2StreamMultiplexer.swift +++ b/Sources/NIOHTTP2/HTTP2StreamMultiplexer.swift @@ -143,7 +143,7 @@ public final class HTTP2StreamMultiplexer: ChannelInboundHandler, ChannelOutboun /// receiving a `PUSH_PROMISE` frame from a server. To initiate a new outbound channel, use /// ``createStreamChannel(promise:_:)-1jk0q``. @available(*, deprecated, renamed: "init(mode:channel:targetWindowSize:outboundBufferSizeHighWatermark:outboundBufferSizeLowWatermark:inboundStreamInitializer:)") - public convenience init(mode: NIOHTTP2Handler.ParserMode, channel: Channel, targetWindowSize: Int = 65535, inboundStreamStateInitializer: ((Channel, HTTP2StreamID) -> EventLoopFuture)? = nil) { + public convenience init(mode: NIOHTTP2Handler.ParserMode, channel: Channel, targetWindowSize: Int = 65535, inboundStreamStateInitializer: NIOChannelInitializerWithStreamID? = nil) { // We default to an 8kB outbound buffer size: this is a good trade off for avoiding excessive buffering while ensuring that decent // throughput can be maintained. We use 4kB as the low water mark. self.init(mode: mode, @@ -176,7 +176,7 @@ public final class HTTP2StreamMultiplexer: ChannelInboundHandler, ChannelOutboun targetWindowSize: Int = 65535, outboundBufferSizeHighWatermark: Int = 8196, outboundBufferSizeLowWatermark: Int = 4092, - inboundStreamInitializer: ((Channel) -> EventLoopFuture)?) { + inboundStreamInitializer: NIOChannelInitializer?) { self.init(mode: mode, channel: channel, targetWindowSize: targetWindowSize, @@ -206,7 +206,7 @@ public final class HTTP2StreamMultiplexer: ChannelInboundHandler, ChannelOutboun targetWindowSize: Int = 65535, outboundBufferSizeHighWatermark: Int, outboundBufferSizeLowWatermark: Int, - inboundStreamStateInitializer: ((Channel, HTTP2StreamID) -> EventLoopFuture)? = nil) { + inboundStreamStateInitializer: NIOChannelInitializerWithStreamID? = nil) { self.init(mode: mode, channel: channel, targetWindowSize: targetWindowSize, @@ -250,7 +250,14 @@ 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 NIOChannelInitializer) { - self.commonStreamMultiplexer.createStreamChannel(multiplexer: .legacy(LegacyOutboundStreamMultiplexer(multiplexer: self)), promise: promise, streamStateInitializer) + let sendableView = HTTP2StreamMultiplexer.SendableView(http2StreamMultiplexer: self, eventLoop: self.channel.eventLoop) + if self.channel.eventLoop.inEventLoop { + sendableView.createStreamChannel(promise: promise, streamStateInitializer) + } else { + self.channel.eventLoop.execute { + sendableView.createStreamChannel(promise: promise, streamStateInitializer) + } + } } /// Create a new `Channel` for a new stream initiated by this peer. @@ -266,8 +273,39 @@ extension HTTP2StreamMultiplexer { /// - streamStateInitializer: A callback that will be invoked to allow you to configure the /// `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.commonStreamMultiplexer.createStreamChannel(multiplexer: .legacy(LegacyOutboundStreamMultiplexer(multiplexer: self)), promise: promise, streamStateInitializer) + public func createStreamChannel(promise: EventLoopPromise?, _ streamStateInitializer: @escaping NIOChannelInitializerWithStreamID) { + let sendableView = HTTP2StreamMultiplexer.SendableView(http2StreamMultiplexer: self, eventLoop: self.channel.eventLoop) + sendableView.createStreamChannel(promise: promise, streamStateInitializer) + } +} + +extension HTTP2StreamMultiplexer { + /// HTTP2StreamMultiplexer.SendableView exposes only the thread-safe API of HTTP2StreamMultiplexer + /// + /// We use unckecked Sendable here because we always make sure we are on the right event loop + /// from this code on. + struct SendableView: @unchecked Sendable { + let http2StreamMultiplexer: HTTP2StreamMultiplexer + let eventLoop: EventLoop + + func createStreamChannel(promise: EventLoopPromise?, _ streamStateInitializer: @escaping NIOChannelInitializer) { + // Always create streams channels on the next event loop tick. This avoids re-entrancy + // issues where handlers interposed between the two HTTP/2 handlers could create streams + // in channel active which become activated twice. + self.eventLoop.execute { + self.http2StreamMultiplexer.commonStreamMultiplexer.createStreamChannel(multiplexer: .legacy(LegacyOutboundStreamMultiplexer(multiplexer: self.http2StreamMultiplexer)), promise: promise, streamStateInitializer) + } + } + + @available(*, deprecated, message: "The signature of 'streamStateInitializer' has changed to '(Channel) -> EventLoopFuture'") + func createStreamChannel(promise: EventLoopPromise?, _ streamStateInitializer: @escaping NIOChannelInitializerWithStreamID) { + // Always create streams channels on the next event loop tick. This avoids re-entrancy + // issues where handlers interposed between the two HTTP/2 handlers could create streams + // in channel active which become activated twice. + self.eventLoop.execute { + self.http2StreamMultiplexer.commonStreamMultiplexer.createStreamChannel(multiplexer: .legacy(LegacyOutboundStreamMultiplexer(multiplexer: self.http2StreamMultiplexer)), promise: promise, streamStateInitializer) + } + } } } diff --git a/Sources/NIOHTTP2/MultiplexerAbstractChannel.swift b/Sources/NIOHTTP2/MultiplexerAbstractChannel.swift index d92a9d5..1117980 100644 --- a/Sources/NIOHTTP2/MultiplexerAbstractChannel.swift +++ b/Sources/NIOHTTP2/MultiplexerAbstractChannel.swift @@ -64,9 +64,9 @@ struct MultiplexerAbstractChannel { extension MultiplexerAbstractChannel { @usableFromInline enum InboundStreamStateInitializer { - case includesStreamID(((Channel, HTTP2StreamID) -> EventLoopFuture)?) - case excludesStreamID(((Channel) -> EventLoopFuture)?) - case returnsAny(((Channel) -> EventLoopFuture)) + case includesStreamID(NIOChannelInitializerWithStreamID?) + case excludesStreamID(NIOChannelInitializer?) + case returnsAny(NIOChannelInitializerWithOutput) } } @@ -105,7 +105,7 @@ extension MultiplexerAbstractChannel { } } - func configureInboundStream(initializer: InboundStreamStateInitializer, promise: EventLoopPromise?) { + func configureInboundStream(initializer: InboundStreamStateInitializer, promise: EventLoopPromise?) { switch initializer { case .includesStreamID, .excludesStreamID: preconditionFailure("Configuration with a supplied `Any` promise is not supported with this initializer type.") @@ -115,7 +115,7 @@ extension MultiplexerAbstractChannel { } // legacy `initializer` function signature - func configure(initializer: ((Channel, HTTP2StreamID) -> EventLoopFuture)?, userPromise promise: EventLoopPromise?) { + func configure(initializer: NIOChannelInitializerWithStreamID?, userPromise promise: EventLoopPromise?) { self.baseChannel.configure(initializer: initializer, userPromise: promise) } @@ -126,7 +126,7 @@ extension MultiplexerAbstractChannel { // used for async multiplexer @usableFromInline - func configure(initializer: @escaping NIOChannelInitializerWithOutput, userPromise promise: EventLoopPromise?) { + func configure(initializer: @escaping NIOChannelInitializerWithOutput, userPromise promise: EventLoopPromise?) { self.baseChannel.configure(initializer: initializer, userPromise: promise) } diff --git a/Sources/NIOHTTP2/UnsafeTransfer.swift b/Sources/NIOHTTP2/UnsafeTransfer.swift new file mode 100644 index 0000000..d1edadc --- /dev/null +++ b/Sources/NIOHTTP2/UnsafeTransfer.swift @@ -0,0 +1,32 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +/// ``UnsafeTransfer`` can be used to make non-`Sendable` values `Sendable`. +/// As the name implies, the usage of this is unsafe because it disables the sendable checking of the compiler. +/// It can be used similar to `@unsafe Sendable` but for values instead of types. +@usableFromInline +struct UnsafeTransfer { + @usableFromInline + var wrappedValue: Wrapped + + @inlinable + init(_ wrappedValue: Wrapped) { + self.wrappedValue = wrappedValue + } +} + +extension UnsafeTransfer: @unchecked Sendable {} + +extension UnsafeTransfer: Equatable where Wrapped: Equatable {} +extension UnsafeTransfer: Hashable where Wrapped: Hashable {} diff --git a/Sources/NIOHTTP2PerformanceTester/Bench1Conn10kRequests.swift b/Sources/NIOHTTP2PerformanceTester/Bench1Conn10kRequests.swift index 9aef49e..1c81b1b 100644 --- a/Sources/NIOHTTP2PerformanceTester/Bench1Conn10kRequests.swift +++ b/Sources/NIOHTTP2PerformanceTester/Bench1Conn10kRequests.swift @@ -86,9 +86,9 @@ func sendOneRequest(channel: Channel, multiplexer: HTTP2StreamMultiplexer) throw ErrorHandler()], position: .last) } - + let loopBoundMultiplexer = NIOLoopBound(multiplexer, eventLoop: channel.eventLoop) channel.eventLoop.execute { - multiplexer.createStreamChannel(promise: nil, requestStreamInitializer) + loopBoundMultiplexer.value.createStreamChannel(promise: nil, requestStreamInitializer) } return try responseReceivedPromise.futureResult.wait() } @@ -115,21 +115,25 @@ final class HTTP1TestServer: ChannelInboundHandler { return } + let loopBoundSelf = NIOLoopBound(self, eventLoop: context.eventLoop) + let loopBoundContext = NIOLoopBound(context, eventLoop: context.eventLoop) + // Insert an event loop tick here. This more accurately represents real workloads in SwiftNIO, which will not // re-entrantly write their response frames. + let channel = context.channel context.eventLoop.execute { - context.channel.getOption(HTTP2StreamChannelOptions.streamID).flatMap { (streamID) -> EventLoopFuture in + channel.getOption(HTTP2StreamChannelOptions.streamID).flatMap { (streamID) -> EventLoopFuture in var headers = HTTPHeaders() headers.add(name: "content-length", value: "5") headers.add(name: "x-stream-id", value: String(Int(streamID))) - context.channel.write(self.wrapOutboundOut(HTTPServerResponsePart.head(HTTPResponseHead(version: .init(major: 2, minor: 0), status: .ok, headers: headers))), promise: nil) + channel.write(loopBoundSelf.value.wrapOutboundOut(HTTPServerResponsePart.head(HTTPResponseHead(version: .init(major: 2, minor: 0), status: .ok, headers: headers))), promise: nil) - var buffer = context.channel.allocator.buffer(capacity: 12) + var buffer = channel.allocator.buffer(capacity: 12) buffer.writeStaticString("hello") - context.channel.write(self.wrapOutboundOut(HTTPServerResponsePart.body(.byteBuffer(buffer))), promise: nil) - return context.channel.writeAndFlush(self.wrapOutboundOut(HTTPServerResponsePart.end(nil))) + channel.write(loopBoundSelf.value.wrapOutboundOut(HTTPServerResponsePart.body(.byteBuffer(buffer))), promise: nil) + return channel.writeAndFlush(loopBoundSelf.value.wrapOutboundOut(HTTPServerResponsePart.end(nil))) }.whenComplete { _ in - context.close(promise: nil) + loopBoundContext.value.close(promise: nil) } } } diff --git a/Sources/NIOHTTP2PerformanceTester/main.swift b/Sources/NIOHTTP2PerformanceTester/main.swift index ff0598d..4cccb91 100644 --- a/Sources/NIOHTTP2PerformanceTester/main.swift +++ b/Sources/NIOHTTP2PerformanceTester/main.swift @@ -17,14 +17,15 @@ import Dispatch // MARK: Test Harness -var warning: String = "" +var _warning: String = "" assert({ print("======================================================") print("= YOU ARE RUNNING NIOPerformanceTester IN DEBUG MODE =") print("======================================================") - warning = " <<< DEBUG MODE >>>" + _warning = " <<< DEBUG MODE >>>" return true }()) +let warning = _warning public func measure(_ fn: () throws -> Int) rethrows -> [TimeInterval] { func measureOne(_ fn: () throws -> Int) rethrows -> TimeInterval { @@ -43,7 +44,7 @@ public func measure(_ fn: () throws -> Int) rethrows -> [TimeInterval] { return measurements } -let limitSet = CommandLine.arguments.dropFirst() +let limitSet = ProcessInfo.processInfo.arguments.dropFirst() public func measureAndPrint(desc: String, fn: () throws -> Int) rethrows -> Void { #if CACHEGRIND diff --git a/Sources/NIOHTTP2Server/main.swift b/Sources/NIOHTTP2Server/main.swift index 908d90f..0c34f68 100644 --- a/Sources/NIOHTTP2Server/main.swift +++ b/Sources/NIOHTTP2Server/main.swift @@ -15,6 +15,7 @@ // This example server currently does not know how to negotiate HTTP/2. That will come in a future enhancement. For now, you can // hit it with curl like so: curl --http2-prior-knowledge http://localhost:8888/ +import Foundation import NIOCore import NIOPosix @@ -44,22 +45,26 @@ final class HTTP1TestServer: ChannelInboundHandler { // Insert an event loop tick here. This more accurately represents real workloads in SwiftNIO, which will not // re-entrantly write their response frames. + let channel = context.channel + let loopBoundContext = NIOLoopBound(context, eventLoop: context.eventLoop) + let loopBoundSelf = NIOLoopBound(self, eventLoop: context.eventLoop) context.eventLoop.execute { - context.channel.getOption(HTTP2StreamChannelOptions.streamID).flatMap { (streamID) -> EventLoopFuture in + channel.getOption(HTTP2StreamChannelOptions.streamID).flatMap { (streamID) -> EventLoopFuture in + let http1TestServer = loopBoundSelf.value var headers = HTTPHeaders() headers.add(name: "content-length", value: "5") headers.add(name: "x-stream-id", value: String(Int(streamID))) - context.channel.write(self.wrapOutboundOut(HTTPServerResponsePart.head(HTTPResponseHead(version: .init(major: 2, minor: 0), status: .ok, headers: headers))), promise: nil) + channel.write(http1TestServer.wrapOutboundOut(HTTPServerResponsePart.head(HTTPResponseHead(version: .init(major: 2, minor: 0), status: .ok, headers: headers))), promise: nil) if requestHead.method != .HEAD { - var buffer = context.channel.allocator.buffer(capacity: 12) + var buffer = channel.allocator.buffer(capacity: 12) buffer.writeStaticString("hello") - context.channel.write(self.wrapOutboundOut(HTTPServerResponsePart.body(.byteBuffer(buffer))), promise: nil) + channel.write(http1TestServer.wrapOutboundOut(HTTPServerResponsePart.body(.byteBuffer(buffer))), promise: nil) } - return context.channel.writeAndFlush(self.wrapOutboundOut(HTTPServerResponsePart.end(nil))) + return channel.writeAndFlush(http1TestServer.wrapOutboundOut(HTTPServerResponsePart.end(nil))) }.whenComplete { _ in - context.close(promise: nil) + loopBoundContext.value.close(promise: nil) } } } @@ -77,7 +82,7 @@ final class ErrorHandler: ChannelInboundHandler { // First argument is the program path -let arguments = CommandLine.arguments +let arguments = ProcessInfo.processInfo.arguments let arg1 = arguments.dropFirst().first let arg2 = arguments.dropFirst().dropFirst().first let arg3 = arguments.dropFirst().dropFirst().dropFirst().first diff --git a/Tests/NIOHTTP2Tests/CompoundOutboundBufferTest.swift b/Tests/NIOHTTP2Tests/CompoundOutboundBufferTest.swift index 9e74535..2f13d7b 100644 --- a/Tests/NIOHTTP2Tests/CompoundOutboundBufferTest.swift +++ b/Tests/NIOHTTP2Tests/CompoundOutboundBufferTest.swift @@ -13,6 +13,7 @@ //===----------------------------------------------------------------------===// import XCTest +import NIOConcurrencyHelpers import NIOCore import NIOEmbedded import NIOHPACK @@ -156,7 +157,7 @@ final class CompoundOutboundBufferTest: XCTestCase { func testBufferedFrameDrops() { var buffer = CompoundOutboundBuffer(mode: .client, initialMaxOutboundStreams: 1, maxBufferedControlFrames: 1000) - var results: [Bool?] = Array(repeating: nil as Bool?, count: 4) + let results = NIOLockedValueBox<[Bool?]>(Array(repeating: nil as Bool?, count: 4)) var futures: [EventLoopFuture] = [] // Write in a bunch of frames, which will get buffered. @@ -180,28 +181,38 @@ final class CompoundOutboundBufferTest: XCTestCase { for (idx, future) in futures.enumerated() { future.map { - results[idx] = true + results.withLockedValue { results in + results[idx] = true + } }.whenFailure { error in XCTAssertEqual(error as? NIOHTTP2Errors.StreamClosed, NIOHTTP2Errors.streamClosed(streamID: 3, errorCode: .protocolError)) - results[idx] = false + results.withLockedValue { results in + results[idx] = false + } } } // Ok, mark the flush point. buffer.flushReceived() - XCTAssertEqual(results, [true, nil, nil, nil]) + results.withLockedValue { results in + XCTAssertEqual(results, [true, nil, nil, nil]) + } // Now, fail stream one. for promise in buffer.streamClosed(1) { promise?.fail(NIOHTTP2Errors.streamClosed(streamID: 3, errorCode: .protocolError)) } - XCTAssertEqual(results, [true, false, nil, nil]) + results.withLockedValue { results in + XCTAssertEqual(results, [true, false, nil, nil]) + } // Now fail stream three. for promise in buffer.streamClosed(3) { promise?.fail(NIOHTTP2Errors.streamClosed(streamID: 3, errorCode: .protocolError)) } - XCTAssertEqual(results, [true, false, false, false]) + results.withLockedValue { results in + XCTAssertEqual(results, [true, false, false, false]) + } } func testRejectsPrioritySelfDependency() { @@ -280,7 +291,7 @@ final class CompoundOutboundBufferTest: XCTestCase { func testFailingAllPromisesOnClose() { var buffer = CompoundOutboundBuffer(mode: .client, initialMaxOutboundStreams: 1, maxBufferedControlFrames: 1000) - var results: [Bool?] = Array(repeating: nil as Bool?, count: 5) + let results = NIOLockedValueBox<[Bool?]>(Array(repeating: nil as Bool?, count: 5)) var futures: [EventLoopFuture] = [] // Write in a bunch of frames, which will get buffered. @@ -309,18 +320,26 @@ final class CompoundOutboundBufferTest: XCTestCase { for (idx, future) in futures.enumerated() { future.map { - results[idx] = false + results.withLockedValue { results in + results[idx] = false + } }.whenFailure { error in XCTAssertEqual(error as? ChannelError, ChannelError.ioOnClosedChannel) - results[idx] = true + results.withLockedValue { results in + results[idx] = true + } } } - XCTAssertEqual(results, [false, nil, nil, nil, nil]) + results.withLockedValue { results in + XCTAssertEqual(results, [false, nil, nil, nil, nil]) + } // Now, invalidate the buffer. buffer.invalidateBuffer() - XCTAssertEqual(results, [false, true, true, true, true]) + results.withLockedValue { results in + XCTAssertEqual(results, [false, true, true, true, true]) + } } func testBufferedControlFramesAreEmittedPreferentiallyToOtherFrames() { @@ -371,18 +390,18 @@ extension CompoundOutboundBuffer { fileprivate mutating func receivedFrames(file: StaticString = #filePath, line: UInt = #line) -> [HTTP2Frame] { var receivedFrames: [HTTP2Frame] = Array() - loop: while true { - switch self.nextFlushedWritableFrame(channelWritable: true) { - case .noFrame: - break loop - case .frame(let bufferedFrame, let promise): - receivedFrames.append(bufferedFrame) - promise?.succeed(()) - case .error(let promise, let error): - promise?.fail(error) - XCTFail("Caught error: \(error)", file: (file), line: line) - } + loop: while true { + switch self.nextFlushedWritableFrame(channelWritable: true) { + case .noFrame: + break loop + case .frame(let bufferedFrame, let promise): + receivedFrames.append(bufferedFrame) + promise?.succeed(()) + case .error(let promise, let error): + promise?.fail(error) + XCTFail("Caught error: \(error)", file: (file), line: line) } + } return receivedFrames } diff --git a/Tests/NIOHTTP2Tests/ConcurrentStreamBufferTest.swift b/Tests/NIOHTTP2Tests/ConcurrentStreamBufferTest.swift index 884a9a6..95e21f1 100644 --- a/Tests/NIOHTTP2Tests/ConcurrentStreamBufferTest.swift +++ b/Tests/NIOHTTP2Tests/ConcurrentStreamBufferTest.swift @@ -13,6 +13,7 @@ //===----------------------------------------------------------------------===// import XCTest +import NIOConcurrencyHelpers import NIOCore import NIOEmbedded import NIOHPACK @@ -236,7 +237,7 @@ final class ConcurrentStreamBufferTests: XCTestCase { XCTAssertNoThrow(try manager.processOutboundFrame(firstFrame, promise: nil, channelWritable: true).assertForward()) manager.streamCreated(1) - var writeStatus: [Bool?] = Array(repeating: nil, count: 30) + let writeStatus = NIOLockedValueBox<[Bool?]>(Array(repeating: nil, count: 30)) var writePromises: [EventLoopFuture] = try assertNoThrowWithValue((0..<15).map { _ in let p = self.loop.makePromise(of: Void.self) @@ -252,10 +253,14 @@ final class ConcurrentStreamBufferTests: XCTestCase { for (idx, promise) in writePromises.enumerated() { promise.map { - writeStatus[idx] = true + writeStatus.withLockedValue { writeStatus in + writeStatus[idx] = true + } }.whenFailure { error in XCTAssertEqual(error as? NIOHTTP2Errors.StreamClosed, NIOHTTP2Errors.streamClosed(streamID: 3, errorCode: .cancel)) - writeStatus[idx] = false + writeStatus.withLockedValue { writeStatus in + writeStatus[idx] = false + } } } @@ -274,7 +279,9 @@ final class ConcurrentStreamBufferTests: XCTestCase { flushedFrames.assertFramesMatch(Array(repeating: subsequentFrame, count: 15)) // Only the first 15 are done. - XCTAssertEqual(writeStatus, Array(repeating: true as Bool?, count: 15) + Array(repeating: nil as Bool?, count: 15)) + writeStatus.withLockedValue { writeStatus in + XCTAssertEqual(writeStatus, Array(repeating: true as Bool?, count: 15) + Array(repeating: nil as Bool?, count: 15)) + } // Now we're going to write a RST_STREAM frame on stream 3 let rstStreamFrame = HTTP2Frame(streamID: 3, payload: .rstStream(.cancel)) @@ -286,7 +293,9 @@ final class ConcurrentStreamBufferTests: XCTestCase { } XCTAssertEqual(error, NIOHTTP2Errors.streamClosed(streamID: 3, errorCode: .cancel)) - XCTAssertEqual(writeStatus, Array(repeating: true as Bool?, count: 15) + Array(repeating: false as Bool?, count: 15)) + writeStatus.withLockedValue { writeStatus in + XCTAssertEqual(writeStatus, Array(repeating: true as Bool?, count: 15) + Array(repeating: false as Bool?, count: 15)) + } } func testResetStreamOnBufferingStream() throws { @@ -298,7 +307,7 @@ final class ConcurrentStreamBufferTests: XCTestCase { XCTAssertNoThrow(try manager.processOutboundFrame(firstFrame, promise: nil, channelWritable: true).assertForward()) manager.streamCreated(1) - var writeStatus: [Bool?] = Array(repeating: nil, count: 15) + let writeStatus = NIOLockedValueBox<[Bool?]>(Array(repeating: nil, count: 15)) let writePromises: [EventLoopFuture] = try assertNoThrowWithValue((0..<15).map { _ in let p = self.loop.makePromise(of: Void.self) @@ -308,16 +317,22 @@ final class ConcurrentStreamBufferTests: XCTestCase { for (idx, promise) in writePromises.enumerated() { promise.map { - writeStatus[idx] = true + writeStatus.withLockedValue { writeStatus in + writeStatus[idx] = true + } }.whenFailure { error in XCTAssertEqual(error as? NIOHTTP2Errors.StreamClosed, NIOHTTP2Errors.streamClosed(streamID: 3, errorCode: .cancel)) - writeStatus[idx] = false + writeStatus.withLockedValue { writeStatus in + writeStatus[idx] = false + } } } // No new writes other than the first frame. XCTAssertNil(manager.nextFlushedWritableFrame()) - XCTAssertEqual(writeStatus, Array(repeating: nil as Bool?, count: 15)) + writeStatus.withLockedValue { writeStatus in + XCTAssertEqual(writeStatus, Array(repeating: nil as Bool?, count: 15)) + } // Now we're going to send RST_STREAM on 3. All writes should fail, and we should be asked to drop the RST_STREAM frame. let rstStreamFrame = HTTP2Frame(streamID: 3, payload: .rstStream(.cancel)) @@ -328,7 +343,9 @@ final class ConcurrentStreamBufferTests: XCTestCase { write.1?.fail(error) } - XCTAssertEqual(writeStatus, Array(repeating: false as Bool?, count: 15)) + writeStatus.withLockedValue { writeStatus in + XCTAssertEqual(writeStatus, Array(repeating: false as Bool?, count: 15)) + } // Flushing changes nothing. manager.flushReceived() @@ -347,7 +364,7 @@ final class ConcurrentStreamBufferTests: XCTestCase { // Now we're going to try to write a frame for stream 5. This will fail. let fiveFrame = HTTP2Frame(streamID: 5, payload: .headers(.init(headers: HPACKHeaders([])))) - + XCTAssertThrowsError(try manager.processOutboundFrame(fiveFrame, promise: nil, channelWritable: true)) { error in XCTAssertTrue(error is NIOHTTP2Errors.StreamIDTooSmall) } @@ -407,7 +424,7 @@ final class ConcurrentStreamBufferTests: XCTestCase { XCTAssertNoThrow(try manager.processOutboundFrame(firstFrame, promise: nil, channelWritable: true).assertForward()) manager.streamCreated(1) - var writeStatus: [Bool?] = Array(repeating: nil, count: 15) + let writeStatus = NIOLockedValueBox<[Bool?]>(Array(repeating: nil, count: 15)) let writePromises: [EventLoopFuture] = try assertNoThrowWithValue((0..<15).map { _ in let p = self.loop.makePromise(of: Void.self) XCTAssertNoThrow(try manager.processOutboundFrame(subsequentFrame, promise: p, channelWritable: true).assertNothing()) @@ -415,10 +432,14 @@ final class ConcurrentStreamBufferTests: XCTestCase { }) for (idx, promise) in writePromises.enumerated() { promise.map { - writeStatus[idx] = true + writeStatus.withLockedValue { writeStatus in + writeStatus[idx] = true + } }.whenFailure { error in XCTAssertEqual(error as? NIOHTTP2Errors.StreamClosed, NIOHTTP2Errors.streamClosed(streamID: 3, errorCode: .protocolError)) - writeStatus[idx] = false + writeStatus.withLockedValue { writeStatus in + writeStatus[idx] = false + } } } manager.flushReceived() @@ -439,7 +460,9 @@ final class ConcurrentStreamBufferTests: XCTestCase { promise?.fail(NIOHTTP2Errors.streamClosed(streamID: 3, errorCode: .protocolError)) } - XCTAssertEqual(writeStatus, Array(repeating: false, count: 15)) + writeStatus.withLockedValue { writeStatus in + XCTAssertEqual(writeStatus, Array(repeating: false, count: 15)) + } } func testBufferingWithBlockedChannel() throws { @@ -452,7 +475,7 @@ final class ConcurrentStreamBufferTests: XCTestCase { // Write a frame for the second stream. This should also be buffered, as the connection still isn't writable. let secondFrame = HTTP2Frame(streamID: 3, payload: .headers(.init(headers: HPACKHeaders()))) XCTAssertNoThrow(try manager.processOutboundFrame(secondFrame, promise: nil, channelWritable: false).assertNothing()) - + manager.flushReceived() // Grab a pending write, simulating the connection becoming writable. diff --git a/Tests/NIOHTTP2Tests/ConfiguringPipelineAsyncMultiplexerTests.swift b/Tests/NIOHTTP2Tests/ConfiguringPipelineAsyncMultiplexerTests.swift index 6af97eb..7a9bc11 100644 --- a/Tests/NIOHTTP2Tests/ConfiguringPipelineAsyncMultiplexerTests.swift +++ b/Tests/NIOHTTP2Tests/ConfiguringPipelineAsyncMultiplexerTests.swift @@ -132,8 +132,8 @@ final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase { } let clientRecorder = try await streamChannel.pipeline.handler(type: InboundFramePayloadRecorder.self).get() - try await self.deliverAllBytes(from: self.clientChannel, to: self.serverChannel) - try await self.deliverAllBytes(from: self.serverChannel, to: self.clientChannel) + try await Self.deliverAllBytes(from: self.clientChannel, to: self.serverChannel) + try await Self.deliverAllBytes(from: self.serverChannel, to: self.clientChannel) clientRecorder.receivedFrames.assertFramePayloadsMatch([ConfiguringPipelineAsyncMultiplexerTests.responseFramePayload]) try await streamChannel.closeFuture.get() } @@ -167,25 +167,26 @@ final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase { ).get() ) - let serverMultiplexer = try await assertNoThrowWithValue( - try await self.serverChannel.configureAsyncHTTP2Pipeline( - mode: .server, - streamInitializer: { channel in - channel.eventLoop.makeCompletedFuture { - try NIOAsyncChannel( - synchronouslyWrapping: channel, - configuration: .init(inboundType: HTTP2Frame.FramePayload.self, outboundType: HTTP2Frame.FramePayload.self) - ) - } + let serverMultiplexerFuture = self.serverChannel.configureAsyncHTTP2Pipeline( + mode: .server, + streamInitializer: { channel in + channel.eventLoop.makeCompletedFuture { + try NIOAsyncChannel( + synchronouslyWrapping: channel, + configuration: .init(inboundType: HTTP2Frame.FramePayload.self, outboundType: HTTP2Frame.FramePayload.self) + ) } - ).get() + } ) try await assertNoThrow(try await self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel)) + let serverChannel = self.serverChannel! + let clientChannel = self.clientChannel! try await withThrowingTaskGroup(of: Int.self, returning: Void.self) { group in // server group.addTask { + let serverMultiplexer = try await assertNoThrowWithValue(try await serverMultiplexerFuture.get()) var serverInboundChannelCount = 0 for try await streamChannel in serverMultiplexer.inbound { for try await receivedFrame in streamChannel.inbound { @@ -194,7 +195,7 @@ final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase { try await streamChannel.outbound.write(ConfiguringPipelineAsyncMultiplexerTests.responseFramePayload) streamChannel.outbound.finish() - try await self.deliverAllBytes(from: self.serverChannel, to: self.clientChannel) + try await Self.deliverAllBytes(from: serverChannel, to: clientChannel) } serverInboundChannelCount += 1 } @@ -218,7 +219,7 @@ final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase { try await streamChannel.outbound.write(ConfiguringPipelineAsyncMultiplexerTests.requestFramePayload) streamChannel.outbound.finish() - try await self.deliverAllBytes(from: self.clientChannel, to: self.serverChannel) + try await Self.deliverAllBytes(from: self.clientChannel, to: self.serverChannel) for try await receivedFrame in streamChannel.inbound { receivedFrame.assertFramePayloadMatches(this: ConfiguringPipelineAsyncMultiplexerTests.responseFramePayload) @@ -257,21 +258,20 @@ final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase { // Let's pretend the TLS handler did protocol negotiation for us self.serverChannel.pipeline.fireUserInboundEventTriggered(TLSUserEvent.handshakeCompleted(negotiatedProtocol: "h2")) - let negotiationResult = try await negotiationResultFuture.get() - try await assertNoThrow(try await self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel)) - let serverMultiplexer: NIOHTTP2Handler.AsyncStreamMultiplexer - switch negotiationResult { - case .http1_1: - preconditionFailure("Negotiation result must be HTTP/2") - case .http2(let (_, multiplexer)): - serverMultiplexer = multiplexer - } - try await withThrowingTaskGroup(of: Int.self, returning: Void.self) { group in // server group.addTask { + let negotiationResult = try await negotiationResultFuture.get() + let serverMultiplexer: NIOHTTP2Handler.AsyncStreamMultiplexer + switch negotiationResult { + case .http1_1: + preconditionFailure("Negotiation result must be HTTP/2") + case .http2(let (_, multiplexer)): + serverMultiplexer = multiplexer + } + var serverInboundChannelCount = 0 for try await _ in serverMultiplexer.inbound { serverInboundChannelCount += 1 @@ -290,8 +290,8 @@ final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase { let clientRecorder = try await streamChannel.pipeline.handler(type: InboundFramePayloadRecorder.self).get() - try await self.deliverAllBytes(from: self.clientChannel, to: self.serverChannel) - try await self.deliverAllBytes(from: self.serverChannel, to: self.clientChannel) + try await Self.deliverAllBytes(from: self.clientChannel, to: self.serverChannel) + try await Self.deliverAllBytes(from: self.serverChannel, to: self.clientChannel) clientRecorder.receivedFrames.assertFramePayloadsMatch([ConfiguringPipelineAsyncMultiplexerTests.responseFramePayload]) try await streamChannel.closeFuture.get() @@ -312,8 +312,8 @@ final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase { func testNegotiatedHTTP1BasicPipelineCommunicates() async throws { let requestCount = 100 - let _ = try await self.clientChannel.pipeline.addHTTPClientHandlers().map { _ in - self.clientChannel.pipeline.addHandlers([InboundRecorderHandler(), HTTP1ClientSendability()]) + let _ = try await self.clientChannel.pipeline.addHTTPClientHandlers().map { [clientChannel = self.clientChannel!] _ in + clientChannel.pipeline.addHandlers([InboundRecorderHandler(), HTTP1ClientSendability()]) }.get() let negotiationResultFuture = try await self.serverChannel.configureAsyncHTTPServerPipeline() { channel in @@ -329,8 +329,8 @@ final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase { let negotiationResult = try await negotiationResultFuture.get() - try await self.deliverAllBytes(from: self.clientChannel, to: self.serverChannel) - try await self.deliverAllBytes(from: self.serverChannel, to: self.clientChannel) + try await Self.deliverAllBytes(from: self.clientChannel, to: self.serverChannel) + try await Self.deliverAllBytes(from: self.serverChannel, to: self.clientChannel) switch negotiationResult { case .http1_1: @@ -345,23 +345,31 @@ final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase { // we need to put these through a mapping to remove references to `IOData` which isn't Sendable try await self.clientChannel.writeOutbound(HTTP1ClientSendability.RequestPart.head(ConfiguringPipelineAsyncMultiplexerTests.requestHead)) try await self.clientChannel.writeOutbound(HTTP1ClientSendability.RequestPart.end(nil)) - try await self.deliverAllBytes(from: self.clientChannel, to: self.serverChannel) - try await self.deliverAllBytes(from: self.serverChannel, to: self.clientChannel) + try await Self.deliverAllBytes(from: self.clientChannel, to: self.serverChannel) + try await Self.deliverAllBytes(from: self.serverChannel, to: self.clientChannel) } // check expectations let clientRecorder = try await self.clientChannel.pipeline.handler(type: InboundRecorderHandler.self).get() let serverRecorder = try await self.serverChannel.pipeline.handler(type: InboundRecorderHandler.self).get() - XCTAssertEqual(serverRecorder.receivedParts.count, requestCount*2) - XCTAssertEqual(clientRecorder.receivedParts.count, requestCount*2) + serverRecorder.receivedParts.withLockedValue { receivedParts in + XCTAssertEqual(receivedParts.count, requestCount*2) + } + clientRecorder.receivedParts.withLockedValue { receivedParts in + XCTAssertEqual(receivedParts.count, requestCount*2) + } for i in 0 ..< requestCount { - XCTAssertEqual(serverRecorder.receivedParts[i*2], HTTPServerRequestPart.head(ConfiguringPipelineAsyncMultiplexerTests.requestHead), "Unexpected request part in iteration \(i)") - XCTAssertEqual(serverRecorder.receivedParts[i*2+1], HTTPServerRequestPart.end(nil), "Unexpected request part in iteration \(i)") + serverRecorder.receivedParts.withLockedValue { receivedParts in + XCTAssertEqual(receivedParts[i*2], HTTPServerRequestPart.head(ConfiguringPipelineAsyncMultiplexerTests.requestHead), "Unexpected request part in iteration \(i)") + XCTAssertEqual(receivedParts[i*2+1], HTTPServerRequestPart.end(nil), "Unexpected request part in iteration \(i)") + } - XCTAssertEqual(clientRecorder.receivedParts[i*2], HTTPClientResponsePart.head(ConfiguringPipelineAsyncMultiplexerTests.responseHead), "Unexpected response part in iteration \(i)") - XCTAssertEqual(clientRecorder.receivedParts[i*2+1], HTTPClientResponsePart.end(nil), "Unexpected response part in iteration \(i)") + clientRecorder.receivedParts.withLockedValue { receivedParts in + XCTAssertEqual(receivedParts[i*2], HTTPClientResponsePart.head(ConfiguringPipelineAsyncMultiplexerTests.responseHead), "Unexpected response part in iteration \(i)") + XCTAssertEqual(receivedParts[i*2+1], HTTPClientResponsePart.end(nil), "Unexpected response part in iteration \(i)") + } } try await assertNoThrow(try await self.clientChannel.finish()) @@ -417,27 +425,15 @@ final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase { } /// A simple channel handler that records inbound messages. - internal final class InboundRecorderHandler: ChannelInboundHandler, @unchecked Sendable { + internal final class InboundRecorderHandler: ChannelInboundHandler, Sendable { typealias InboundIn = message - private let partsLock = NIOLock() - private var _receivedParts: [message] = [] - - var receivedParts: [message] { - get { - self.partsLock.withLock { - self._receivedParts - } - } - set { - self.partsLock.withLock { - self._receivedParts = newValue - } - } - } + let receivedParts = NIOLockedValueBox<[message]>([]) func channelRead(context: ChannelHandlerContext, data: NIOAny) { - self.receivedParts.append(self.unwrapInboundIn(data)) + self.receivedParts.withLockedValue { receivedParts in + receivedParts.append(self.unwrapInboundIn(data)) + } context.fireChannelRead(data) } } @@ -446,7 +442,7 @@ final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase { #if swift(<5.9) // this should be available in the std lib from 5.9 onwards extension AsyncStream { - fileprivate static func makeStream( + internal static func makeStream( of elementType: Element.Type = Element.self, bufferingPolicy limit: Continuation.BufferingPolicy = .unbounded ) -> (stream: AsyncStream, continuation: AsyncStream.Continuation) { diff --git a/Tests/NIOHTTP2Tests/ConfiguringPipelineInlineMultiplexerTests.swift b/Tests/NIOHTTP2Tests/ConfiguringPipelineInlineMultiplexerTests.swift index 7fcf056..5592a6d 100644 --- a/Tests/NIOHTTP2Tests/ConfiguringPipelineInlineMultiplexerTests.swift +++ b/Tests/NIOHTTP2Tests/ConfiguringPipelineInlineMultiplexerTests.swift @@ -14,6 +14,7 @@ import XCTest +import NIOConcurrencyHelpers import NIOCore import NIOEmbedded import NIOHPACK @@ -37,7 +38,14 @@ class ConfiguringPipelineInlineMultiplexerTests: XCTestCase { func testBasicPipelineCommunicates() throws { let serverRecorder = InboundFramePayloadRecorder() - let clientMultiplexer = try assertNoThrowWithValue(self.clientChannel.configureHTTP2Pipeline(mode: .client, connectionConfiguration: .init(), streamConfiguration: .init(), inboundStreamInitializer: {_ in self.clientChannel.eventLoop.makeSucceededVoidFuture()} ).wait()) + let clientMultiplexer = try self.clientChannel.configureHTTP2Pipeline( + mode: .client, + connectionConfiguration: .init(), + streamConfiguration: .init(), + inboundStreamInitializer: { clientChannel in + clientChannel.eventLoop.makeSucceededVoidFuture() + } + ).wait() XCTAssertNoThrow(try self.serverChannel.configureHTTP2Pipeline(mode: .server, connectionConfiguration: .init(), streamConfiguration: .init()) { channel in return channel.pipeline.addHandler(serverRecorder) }.wait()) @@ -76,7 +84,14 @@ class ConfiguringPipelineInlineMultiplexerTests: XCTestCase { func testBasicPipelineCommunicatesWithTargetWindowSize() throws { let serverRecorder = InboundFramePayloadRecorder() - let clientMultiplexer = try assertNoThrowWithValue(self.clientChannel.configureHTTP2Pipeline(mode: .client, connectionConfiguration: .init(), streamConfiguration: .init(), inboundStreamInitializer: {_ in self.clientChannel.eventLoop.makeSucceededVoidFuture()} ).wait()) + let clientMultiplexer = try self.clientChannel.configureHTTP2Pipeline( + mode: .client, + connectionConfiguration: .init(), + streamConfiguration: .init(), + inboundStreamInitializer: { clientChannel in + clientChannel.eventLoop.makeSucceededVoidFuture() + } + ).wait() XCTAssertNoThrow(try self.serverChannel.configureHTTP2Pipeline(mode: .server, connectionConfiguration: .init(), streamConfiguration: .init()) { channel in return channel.pipeline.addHandler(serverRecorder) }.wait()) @@ -115,8 +130,19 @@ class ConfiguringPipelineInlineMultiplexerTests: XCTestCase { func testPipelineRespectsPositionRequest() throws { XCTAssertNoThrow(try self.clientChannel.pipeline.addHandler(FailOnWriteHandler()).wait()) - XCTAssertNoThrow(try self.clientChannel.configureHTTP2Pipeline(mode: .client, connectionConfiguration: .init(), streamConfiguration: .init(), position: .first, inboundStreamInitializer: {_ in self.clientChannel.eventLoop.makeSucceededVoidFuture()} ).wait()) - XCTAssertNoThrow(try self.serverChannel.configureHTTP2Pipeline(mode: .server, connectionConfiguration: .init(), streamConfiguration: .init(), inboundStreamInitializer: {_ in self.clientChannel.eventLoop.makeSucceededVoidFuture()} ).wait()) + _ = try self.clientChannel.configureHTTP2Pipeline( + mode: .client, + connectionConfiguration: .init(), + streamConfiguration: .init(), + position: .first, + inboundStreamInitializer: { channel in channel.eventLoop.makeSucceededVoidFuture()} + ).wait() + _ = try self.serverChannel.configureHTTP2Pipeline( + mode: .server, + connectionConfiguration: .init(), + streamConfiguration: .init(), + inboundStreamInitializer: { channel in channel.eventLoop.makeSucceededVoidFuture()} + ).wait() XCTAssertNoThrow(try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel)) @@ -132,8 +158,19 @@ class ConfiguringPipelineInlineMultiplexerTests: XCTestCase { func testPipelineRespectsPositionRequestWithTargetWindowSize() throws { XCTAssertNoThrow(try self.clientChannel.pipeline.addHandler(FailOnWriteHandler()).wait()) - XCTAssertNoThrow(try self.clientChannel.configureHTTP2Pipeline(mode: .client, connectionConfiguration: .init(), streamConfiguration: .init(), position: .first, inboundStreamInitializer: {_ in self.clientChannel.eventLoop.makeSucceededVoidFuture()} ).wait()) - XCTAssertNoThrow(try self.serverChannel.configureHTTP2Pipeline(mode: .server, connectionConfiguration: .init(), streamConfiguration: .init(), inboundStreamInitializer: {_ in self.clientChannel.eventLoop.makeSucceededVoidFuture()} ).wait()) + _ = try self.clientChannel.configureHTTP2Pipeline( + mode: .client, + connectionConfiguration: .init(), + streamConfiguration: .init(), + position: .first, + inboundStreamInitializer: { channel in channel.eventLoop.makeSucceededVoidFuture()} + ).wait() + _ = try self.serverChannel.configureHTTP2Pipeline( + mode: .server, + connectionConfiguration: .init(), + streamConfiguration: .init(), + inboundStreamInitializer: { channel in channel.eventLoop.makeSucceededVoidFuture()} + ).wait() XCTAssertNoThrow(try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel)) @@ -152,11 +189,17 @@ class ConfiguringPipelineInlineMultiplexerTests: XCTestCase { // to sending the preamble, in handlerAdded(context:) (if the channel is active) and in channelActive(context:), // we want to hit both of these. let connectionPromise: EventLoopPromise = self.serverChannel.eventLoop.makePromise() + let serverChannel = self.serverChannel! // Register the callback on the promise so we run it as it succeeds (i.e. before fireChannelActive is called). let handlerAdded = connectionPromise.futureResult.flatMap { // Use .server to avoid sending client magic. - self.serverChannel.configureHTTP2Pipeline(mode: .server, connectionConfiguration: .init(), streamConfiguration: .init(), inboundStreamInitializer: {_ in self.clientChannel.eventLoop.makeSucceededVoidFuture()} ) + serverChannel.configureHTTP2Pipeline( + mode: .server, + connectionConfiguration: .init(), + streamConfiguration: .init(), + inboundStreamInitializer: { channel in channel.eventLoop.makeSucceededVoidFuture() } + ) } self.serverChannel.connect(to: try SocketAddress(unixDomainSocketPath: "/fake"), promise: connectionPromise) @@ -185,11 +228,16 @@ class ConfiguringPipelineInlineMultiplexerTests: XCTestCase { // to sending the preamble, in handlerAdded(context:) (if the channel is active) and in channelActive(context:), // we want to hit both of these. let connectionPromise: EventLoopPromise = self.serverChannel.eventLoop.makePromise() + let serverChannel = self.serverChannel! // Register the callback on the promise so we run it as it succeeds (i.e. before fireChannelActive is called). let handlerAdded = connectionPromise.futureResult.flatMap { - // Use .server to avoid sending client magic. - self.serverChannel.configureHTTP2Pipeline(mode: .server, connectionConfiguration: .init(), streamConfiguration: .init(), inboundStreamInitializer: {_ in self.clientChannel.eventLoop.makeSucceededVoidFuture()} ) + serverChannel.configureHTTP2Pipeline( + mode: .server, + connectionConfiguration: .init(), + streamConfiguration: .init(), + inboundStreamInitializer: { channel in channel.eventLoop.makeSucceededVoidFuture()} + ) } self.serverChannel.connect(to: try SocketAddress(unixDomainSocketPath: "/fake"), promise: connectionPromise) @@ -229,8 +277,20 @@ class ConfiguringPipelineInlineMultiplexerTests: XCTestCase { } } - let clientMultiplexer = try assertNoThrowWithValue(self.clientChannel.configureHTTP2Pipeline(mode: .client, connectionConfiguration: .init(), streamConfiguration: .init(), inboundStreamInitializer: {_ in self.clientChannel.eventLoop.makeSucceededVoidFuture()} ).wait()) - XCTAssertNoThrow(try self.serverChannel.configureHTTP2Pipeline(mode: .server, connectionConfiguration: .init(), streamConfiguration: .init(), inboundStreamInitializer: {_ in self.clientChannel.eventLoop.makeSucceededVoidFuture()} ).wait()) + let clientMultiplexer = try self.clientChannel.configureHTTP2Pipeline( + mode: .client, + connectionConfiguration: .init(), + streamConfiguration: .init(), + inboundStreamInitializer: { clientChannel in + clientChannel.eventLoop.makeSucceededVoidFuture() + } + ).wait() + _ = try self.serverChannel.configureHTTP2Pipeline( + mode: .server, + connectionConfiguration: .init(), + streamConfiguration: .init(), + inboundStreamInitializer: { channel in channel.eventLoop.makeSucceededVoidFuture()} + ).wait() XCTAssertNoThrow(try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel)) @@ -272,8 +332,20 @@ class ConfiguringPipelineInlineMultiplexerTests: XCTestCase { } } - let clientMultiplexer = try assertNoThrowWithValue(self.clientChannel.configureHTTP2Pipeline(mode: .client, connectionConfiguration: .init(), streamConfiguration: .init(), inboundStreamInitializer: {_ in self.clientChannel.eventLoop.makeSucceededVoidFuture()} ).wait()) - XCTAssertNoThrow(try self.serverChannel.configureHTTP2Pipeline(mode: .server, connectionConfiguration: .init(), streamConfiguration: .init(), inboundStreamInitializer: {_ in self.clientChannel.eventLoop.makeSucceededVoidFuture()} ).wait()) + let clientMultiplexer = try self.clientChannel.configureHTTP2Pipeline( + mode: .client, + connectionConfiguration: .init(), + streamConfiguration: .init(), + inboundStreamInitializer: { clientChannel in + clientChannel.eventLoop.makeSucceededVoidFuture() + } + ).wait() + _ = try self.serverChannel.configureHTTP2Pipeline( + mode: .server, + connectionConfiguration: .init(), + streamConfiguration: .init(), + inboundStreamInitializer: { channel in channel.eventLoop.makeSucceededVoidFuture()} + ).wait() XCTAssertNoThrow(try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel)) @@ -300,13 +372,15 @@ class ConfiguringPipelineInlineMultiplexerTests: XCTestCase { } /// A simple channel handler that records inbound frames. - class HTTP1ServerRequestRecorderHandler: ChannelInboundHandler { + final class HTTP1ServerRequestRecorderHandler: ChannelInboundHandler, Sendable { typealias InboundIn = HTTPServerRequestPart - var receivedParts: [HTTPServerRequestPart] = [] + let receivedParts = NIOLockedValueBox<[HTTPServerRequestPart]>([]) func channelRead(context: ChannelHandlerContext, data: NIOAny) { - self.receivedParts.append(self.unwrapInboundIn(data)) + self.receivedParts.withLockedValue { receivedParts in + receivedParts.append(self.unwrapInboundIn(data)) + } } } @@ -318,9 +392,15 @@ class ConfiguringPipelineInlineMultiplexerTests: XCTestCase { context.close(promise: nil) } } - let serverRecorder = HTTP1ServerRequestRecorderHandler() - let clientMultiplexer = try assertNoThrowWithValue(self.clientChannel.configureHTTP2Pipeline(mode: .client, connectionConfiguration: .init(), streamConfiguration: .init(), inboundStreamInitializer: {_ in self.clientChannel.eventLoop.makeSucceededVoidFuture()} ).wait()) + let clientMultiplexer = try self.clientChannel.configureHTTP2Pipeline( + mode: .client, + connectionConfiguration: .init(), + streamConfiguration: .init(), + inboundStreamInitializer: { clientChannel in + clientChannel.eventLoop.makeSucceededVoidFuture() + } + ).wait() XCTAssertNoThrow(try self.serverChannel.configureCommonHTTPServerPipeline( connectionConfiguration: .init(), @@ -356,18 +436,20 @@ class ConfiguringPipelineInlineMultiplexerTests: XCTestCase { // Assert that the user-provided handler received the // HTTP1 parts corresponding to the H2 message sent - XCTAssertEqual(2, serverRecorder.receivedParts.count) - if case .some(.head(let head)) = serverRecorder.receivedParts.first { - XCTAssertEqual(1, head.headers["host"].count) - XCTAssertEqual("localhost", head.headers["host"].first) - XCTAssertEqual(.GET, head.method) - XCTAssertEqual("/testH2toHTTP1", head.uri) - } else { - XCTFail("Expected head") - } - if case .some(.end(_)) = serverRecorder.receivedParts.last { - } else { - XCTFail("Expected end") + serverRecorder.receivedParts.withLockedValue { receivedParts in + XCTAssertEqual(2, receivedParts.count) + if case .some(.head(let head)) = receivedParts.first { + XCTAssertEqual(1, head.headers["host"].count) + XCTAssertEqual("localhost", head.headers["host"].first) + XCTAssertEqual(.GET, head.method) + XCTAssertEqual("/testH2toHTTP1", head.uri) + } else { + XCTFail("Expected head") + } + if case .some(.end(_)) = receivedParts.last { + } else { + XCTFail("Expected end") + } } self.clientChannel.assertNoFramesReceived() self.serverChannel.assertNoFramesReceived() @@ -386,7 +468,14 @@ class ConfiguringPipelineInlineMultiplexerTests: XCTestCase { } let serverRecorder = HTTP1ServerRequestRecorderHandler() - let clientMultiplexer = try assertNoThrowWithValue(self.clientChannel.configureHTTP2Pipeline(mode: .client, connectionConfiguration: .init(), streamConfiguration: .init(), inboundStreamInitializer: {_ in self.clientChannel.eventLoop.makeSucceededVoidFuture()} ).wait()) + let clientMultiplexer = try self.clientChannel.configureHTTP2Pipeline( + mode: .client, + connectionConfiguration: .init(), + streamConfiguration: .init(), + inboundStreamInitializer: { clientChannel in + clientChannel.eventLoop.makeSucceededVoidFuture() + } + ).wait() XCTAssertNoThrow(try self.serverChannel.configureCommonHTTPServerPipeline( connectionConfiguration: .init(), @@ -422,18 +511,20 @@ class ConfiguringPipelineInlineMultiplexerTests: XCTestCase { // Assert that the user-provided handler received the // HTTP1 parts corresponding to the H2 message sent - XCTAssertEqual(2, serverRecorder.receivedParts.count) - if case .some(.head(let head)) = serverRecorder.receivedParts.first { - XCTAssertEqual(1, head.headers["host"].count) - XCTAssertEqual("localhost", head.headers["host"].first) - XCTAssertEqual(.GET, head.method) - XCTAssertEqual("/testH2toHTTP1", head.uri) - } else { - XCTFail("Expected head") - } - if case .some(.end(_)) = serverRecorder.receivedParts.last { - } else { - XCTFail("Expected end") + serverRecorder.receivedParts.withLockedValue { receivedParts in + XCTAssertEqual(2, receivedParts.count) + if case .some(.head(let head)) = receivedParts.first { + XCTAssertEqual(1, head.headers["host"].count) + XCTAssertEqual("localhost", head.headers["host"].first) + XCTAssertEqual(.GET, head.method) + XCTAssertEqual("/testH2toHTTP1", head.uri) + } else { + XCTFail("Expected head") + } + if case .some(.end(_)) = receivedParts.last { + } else { + XCTFail("Expected end") + } } self.clientChannel.assertNoFramesReceived() self.serverChannel.assertNoFramesReceived() @@ -477,16 +568,18 @@ class ConfiguringPipelineInlineMultiplexerTests: XCTestCase { // Assert that the user-provided handler received the // HTTP1 parts corresponding to the H2 message sent - XCTAssertEqual(2, serverRecorder.receivedParts.count) - if case .some(.head(let head)) = serverRecorder.receivedParts.first { - XCTAssertEqual(.GET, head.method) - XCTAssertEqual("/testHTTP1", head.uri) - } else { - XCTFail("Expected head") - } - if case .some(.end(_)) = serverRecorder.receivedParts.last { - } else { - XCTFail("Expected end") + serverRecorder.receivedParts.withLockedValue { receivedParts in + XCTAssertEqual(2, receivedParts.count) + if case .some(.head(let head)) = receivedParts.first { + XCTAssertEqual(.GET, head.method) + XCTAssertEqual("/testHTTP1", head.uri) + } else { + XCTFail("Expected head") + } + if case .some(.end(_)) = receivedParts.last { + } else { + XCTFail("Expected end") + } } self.clientChannel.assertNoFramesReceived() self.serverChannel.assertNoFramesReceived() diff --git a/Tests/NIOHTTP2Tests/ConfiguringPipelineTests.swift b/Tests/NIOHTTP2Tests/ConfiguringPipelineTests.swift index 122a3fb..a284d34 100644 --- a/Tests/NIOHTTP2Tests/ConfiguringPipelineTests.swift +++ b/Tests/NIOHTTP2Tests/ConfiguringPipelineTests.swift @@ -14,6 +14,7 @@ import XCTest +import NIOConcurrencyHelpers import NIOCore import NIOEmbedded import NIOHPACK @@ -160,10 +161,12 @@ class ConfiguringPipelineTests: XCTestCase { // we want to hit both of these. let connectionPromise: EventLoopPromise = self.serverChannel.eventLoop.makePromise() + let serverChannel = self.serverChannel! + // Register the callback on the promise so we run it as it succeeds (i.e. before fireChannelActive is called). let handlerAdded = connectionPromise.futureResult.flatMap { // Use .server to avoid sending client magic. - self.serverChannel.configureHTTP2Pipeline(mode: .server) + serverChannel.configureHTTP2Pipeline(mode: .server) } self.serverChannel.connect(to: try SocketAddress(unixDomainSocketPath: "/fake"), promise: connectionPromise) @@ -194,10 +197,12 @@ class ConfiguringPipelineTests: XCTestCase { // we want to hit both of these. let connectionPromise: EventLoopPromise = self.serverChannel.eventLoop.makePromise() + let serverChannel = self.serverChannel! + // Register the callback on the promise so we run it as it succeeds (i.e. before fireChannelActive is called). let handlerAdded = connectionPromise.futureResult.flatMap { // Use .server to avoid sending client magic. - self.serverChannel.configureHTTP2Pipeline(mode: .server, targetWindowSize: 65535) + serverChannel.configureHTTP2Pipeline(mode: .server, targetWindowSize: 65535) } self.serverChannel.connect(to: try SocketAddress(unixDomainSocketPath: "/fake"), promise: connectionPromise) @@ -310,13 +315,15 @@ class ConfiguringPipelineTests: XCTestCase { } /// A simple channel handler that records inbound frames. - class HTTP1ServerRequestRecorderHandler: ChannelInboundHandler { + final class HTTP1ServerRequestRecorderHandler: ChannelInboundHandler, Sendable { typealias InboundIn = HTTPServerRequestPart - var receivedParts: [HTTPServerRequestPart] = [] + let receivedParts = NIOLockedValueBox<[HTTPServerRequestPart]>([]) func channelRead(context: ChannelHandlerContext, data: NIOAny) { - self.receivedParts.append(self.unwrapInboundIn(data)) + self.receivedParts.withLockedValue { receivedParts in + receivedParts.append(self.unwrapInboundIn(data)) + } } } @@ -330,11 +337,12 @@ class ConfiguringPipelineTests: XCTestCase { } } - let serverRecorder = HTTP1ServerRequestRecorderHandler() let clientHandler = try assertNoThrowWithValue(self.clientChannel.configureHTTP2Pipeline(mode: .client).wait()) + let serverChildChannelPromise = self.serverChannel.eventLoop.makePromise(of: Channel.self) XCTAssertNoThrow(try self.serverChannel.configureCommonHTTPServerPipeline(h2ConnectionChannelConfigurator: { $0.pipeline.addHandler(ErrorHandler()) }) { channel in - return channel.pipeline.addHandler(serverRecorder) + serverChildChannelPromise.succeed(channel) + return channel.pipeline.addHandler(HTTP1ServerRequestRecorderHandler()) }.wait()) // Let's pretend the TLS handler did protocol negotiation for us @@ -361,21 +369,27 @@ class ConfiguringPipelineTests: XCTestCase { XCTAssertTrue(error is NIOHTTP2Errors.StreamClosed) } - // Assert that the user-provided handler received the - // HTTP1 parts corresponding to the H2 message sent - XCTAssertEqual(2, serverRecorder.receivedParts.count) - if case .some(.head(let head)) = serverRecorder.receivedParts.first { - XCTAssertEqual(1, head.headers["host"].count) - XCTAssertEqual("localhost", head.headers["host"].first) - XCTAssertEqual(.GET, head.method) - XCTAssertEqual("/testH2toHTTP1", head.uri) - } else { - XCTFail("Expected head") - } - if case .some(.end(_)) = serverRecorder.receivedParts.last { - } else { - XCTFail("Expected end") - } + let serverChildChannel = try serverChildChannelPromise.futureResult.wait() + try serverChildChannel.pipeline.handler(type: HTTP1ServerRequestRecorderHandler.self).map { serverRecorder in + // Assert that the user-provided handler received the + // HTTP1 parts corresponding to the H2 message sent + serverRecorder.receivedParts.withLockedValue { receivedParts in + XCTAssertEqual(2, receivedParts.count) + if case .some(.head(let head)) = receivedParts.first { + XCTAssertEqual(1, head.headers["host"].count) + XCTAssertEqual("localhost", head.headers["host"].first) + XCTAssertEqual(.GET, head.method) + XCTAssertEqual("/testH2toHTTP1", head.uri) + } else { + XCTFail("Expected head") + } + if case .some(.end(_)) = receivedParts.last { + } else { + XCTFail("Expected end") + } + } + }.wait() + self.clientChannel.assertNoFramesReceived() self.serverChannel.assertNoFramesReceived() @@ -393,11 +407,12 @@ class ConfiguringPipelineTests: XCTestCase { } } - let serverRecorder = HTTP1ServerRequestRecorderHandler() let clientHandler = try assertNoThrowWithValue(self.clientChannel.configureHTTP2Pipeline(mode: .client, targetWindowSize: 65535).wait()) + let serverChildChannelPromise = self.serverChannel.eventLoop.makePromise(of: Channel.self) XCTAssertNoThrow(try self.serverChannel.configureCommonHTTPServerPipeline(h2ConnectionChannelConfigurator: { $0.pipeline.addHandler(ErrorHandler()) }) { channel in - return channel.pipeline.addHandler(serverRecorder) + serverChildChannelPromise.succeed(channel) + return channel.pipeline.addHandler(HTTP1ServerRequestRecorderHandler()) }.wait()) // Let's pretend the TLS handler did protocol negotiation for us @@ -424,21 +439,27 @@ class ConfiguringPipelineTests: XCTestCase { XCTAssertTrue(error is NIOHTTP2Errors.StreamClosed) } - // Assert that the user-provided handler received the - // HTTP1 parts corresponding to the H2 message sent - XCTAssertEqual(2, serverRecorder.receivedParts.count) - if case .some(.head(let head)) = serverRecorder.receivedParts.first { - XCTAssertEqual(1, head.headers["host"].count) - XCTAssertEqual("localhost", head.headers["host"].first) - XCTAssertEqual(.GET, head.method) - XCTAssertEqual("/testH2toHTTP1", head.uri) - } else { - XCTFail("Expected head") - } - if case .some(.end(_)) = serverRecorder.receivedParts.last { - } else { - XCTFail("Expected end") - } + let serverChildChannel = try serverChildChannelPromise.futureResult.wait() + try serverChildChannel.pipeline.handler(type: HTTP1ServerRequestRecorderHandler.self).map { serverRecorder in + // Assert that the user-provided handler received the + // HTTP1 parts corresponding to the H2 message sent + serverRecorder.receivedParts.withLockedValue { receivedParts in + XCTAssertEqual(2, receivedParts.count) + if case .some(.head(let head)) = receivedParts.first { + XCTAssertEqual(1, head.headers["host"].count) + XCTAssertEqual("localhost", head.headers["host"].first) + XCTAssertEqual(.GET, head.method) + XCTAssertEqual("/testH2toHTTP1", head.uri) + } else { + XCTFail("Expected head") + } + if case .some(.end(_)) = receivedParts.last { + } else { + XCTFail("Expected end") + } + } + }.wait() + self.clientChannel.assertNoFramesReceived() self.serverChannel.assertNoFramesReceived() diff --git a/Tests/NIOHTTP2Tests/ConfiguringPipelineWithFramePayloadStreamsTests.swift b/Tests/NIOHTTP2Tests/ConfiguringPipelineWithFramePayloadStreamsTests.swift index 1032333..5d7164c 100644 --- a/Tests/NIOHTTP2Tests/ConfiguringPipelineWithFramePayloadStreamsTests.swift +++ b/Tests/NIOHTTP2Tests/ConfiguringPipelineWithFramePayloadStreamsTests.swift @@ -15,6 +15,7 @@ import XCTest import NIOCore +import NIOConcurrencyHelpers import NIOEmbedded import NIOHPACK import NIOHTTP1 @@ -86,7 +87,7 @@ class ConfiguringPipelineWithFramePayloadStreamsTests: XCTestCase { XCTAssertNoThrow(try self.clientChannel.finish()) XCTAssertNoThrow(try self.serverChannel.finish()) } - + func testBasicPipelineCommunicatesWithTargetWindowSize() throws { let serverRecorder = InboundFramePayloadRecorder() let clientHandler = try assertNoThrowWithValue(self.clientChannel.configureHTTP2Pipeline(mode: .client, targetWindowSize: 65535, inboundStreamInitializer: nil).wait()) @@ -159,17 +160,19 @@ class ConfiguringPipelineWithFramePayloadStreamsTests: XCTestCase { XCTAssertNoThrow(try self.clientChannel.finish()) XCTAssertNoThrow(try self.serverChannel.finish()) } - + func testPreambleGetsWrittenOnce() throws { // This test checks that the preamble sent by NIOHTTP2Handler is only written once. There are two paths // to sending the preamble, in handlerAdded(context:) (if the channel is active) and in channelActive(context:), // we want to hit both of these. let connectionPromise: EventLoopPromise = self.serverChannel.eventLoop.makePromise() + let serverChannel = self.serverChannel! + // Register the callback on the promise so we run it as it succeeds (i.e. before fireChannelActive is called). let handlerAdded = connectionPromise.futureResult.flatMap { // Use .server to avoid sending client magic. - self.serverChannel.configureHTTP2Pipeline(mode: .server, inboundStreamInitializer: nil) + serverChannel.configureHTTP2Pipeline(mode: .server, inboundStreamInitializer: nil) } self.serverChannel.connect(to: try SocketAddress(unixDomainSocketPath: "/fake"), promise: connectionPromise) @@ -199,10 +202,12 @@ class ConfiguringPipelineWithFramePayloadStreamsTests: XCTestCase { // we want to hit both of these. let connectionPromise: EventLoopPromise = self.serverChannel.eventLoop.makePromise() + let serverChannel = self.serverChannel! + // Register the callback on the promise so we run it as it succeeds (i.e. before fireChannelActive is called). let handlerAdded = connectionPromise.futureResult.flatMap { // Use .server to avoid sending client magic. - self.serverChannel.configureHTTP2Pipeline(mode: .server, targetWindowSize: 65535, inboundStreamInitializer: nil) + serverChannel.configureHTTP2Pipeline(mode: .server, targetWindowSize: 65535, inboundStreamInitializer: nil) } self.serverChannel.connect(to: try SocketAddress(unixDomainSocketPath: "/fake"), promise: connectionPromise) @@ -225,7 +230,7 @@ class ConfiguringPipelineWithFramePayloadStreamsTests: XCTestCase { // We don't expect anything else at this point. XCTAssertNil(try self.serverChannel.readOutbound(as: IOData.self)) } - + func testClosingParentChannelClosesStreamChannel() throws { /// A channel handler that succeeds a promise when the channel becomes inactive. final class InactiveHandler: ChannelInboundHandler { @@ -268,7 +273,7 @@ class ConfiguringPipelineWithFramePayloadStreamsTests: XCTestCase { } XCTAssertNoThrow(try self.serverChannel.finish()) } - + func testClosingParentChannelClosesStreamChannelWithTargetWindowSize() throws { /// A channel handler that succeeds a promise when the channel becomes inactive. final class InactiveHandler: ChannelInboundHandler { @@ -313,13 +318,15 @@ class ConfiguringPipelineWithFramePayloadStreamsTests: XCTestCase { } /// A simple channel handler that records inbound frames. - class HTTP1ServerRequestRecorderHandler: ChannelInboundHandler { + final class HTTP1ServerRequestRecorderHandler: ChannelInboundHandler, Sendable { typealias InboundIn = HTTPServerRequestPart - var receivedParts: [HTTPServerRequestPart] = [] + let receivedParts = NIOLockedValueBox<[HTTPServerRequestPart]>([]) func channelRead(context: ChannelHandlerContext, data: NIOAny) { - self.receivedParts.append(self.unwrapInboundIn(data)) + self.receivedParts.withLockedValue { receivedParts in + receivedParts.append(self.unwrapInboundIn(data)) + } } } @@ -364,18 +371,20 @@ class ConfiguringPipelineWithFramePayloadStreamsTests: XCTestCase { // Assert that the user-provided handler received the // HTTP1 parts corresponding to the H2 message sent - XCTAssertEqual(2, serverRecorder.receivedParts.count) - if case .some(.head(let head)) = serverRecorder.receivedParts.first { - XCTAssertEqual(1, head.headers["host"].count) - XCTAssertEqual("localhost", head.headers["host"].first) - XCTAssertEqual(.GET, head.method) - XCTAssertEqual("/testH2toHTTP1", head.uri) - } else { - XCTFail("Expected head") - } - if case .some(.end(_)) = serverRecorder.receivedParts.last { - } else { - XCTFail("Expected end") + serverRecorder.receivedParts.withLockedValue { receivedParts in + XCTAssertEqual(2, receivedParts.count) + if case .some(.head(let head)) = receivedParts.first { + XCTAssertEqual(1, head.headers["host"].count) + XCTAssertEqual("localhost", head.headers["host"].first) + XCTAssertEqual(.GET, head.method) + XCTAssertEqual("/testH2toHTTP1", head.uri) + } else { + XCTFail("Expected head") + } + if case .some(.end(_)) = receivedParts.last { + } else { + XCTFail("Expected end") + } } self.clientChannel.assertNoFramesReceived() self.serverChannel.assertNoFramesReceived() @@ -383,7 +392,7 @@ class ConfiguringPipelineWithFramePayloadStreamsTests: XCTestCase { XCTAssertNoThrow(try self.clientChannel.finish()) XCTAssertNoThrow(try self.serverChannel.finish()) } - + func testNegotiatedHTTP2BasicPipelineCommunicatesWithTargetWindowSize() throws { final class ErrorHandler: ChannelInboundHandler { typealias InboundIn = Never @@ -425,18 +434,20 @@ class ConfiguringPipelineWithFramePayloadStreamsTests: XCTestCase { // Assert that the user-provided handler received the // HTTP1 parts corresponding to the H2 message sent - XCTAssertEqual(2, serverRecorder.receivedParts.count) - if case .some(.head(let head)) = serverRecorder.receivedParts.first { - XCTAssertEqual(1, head.headers["host"].count) - XCTAssertEqual("localhost", head.headers["host"].first) - XCTAssertEqual(.GET, head.method) - XCTAssertEqual("/testH2toHTTP1", head.uri) - } else { - XCTFail("Expected head") - } - if case .some(.end(_)) = serverRecorder.receivedParts.last { - } else { - XCTFail("Expected end") + serverRecorder.receivedParts.withLockedValue { receivedParts in + XCTAssertEqual(2, receivedParts.count) + if case .some(.head(let head)) = receivedParts.first { + XCTAssertEqual(1, head.headers["host"].count) + XCTAssertEqual("localhost", head.headers["host"].first) + XCTAssertEqual(.GET, head.method) + XCTAssertEqual("/testH2toHTTP1", head.uri) + } else { + XCTFail("Expected head") + } + if case .some(.end(_)) = receivedParts.last { + } else { + XCTFail("Expected end") + } } self.clientChannel.assertNoFramesReceived() self.serverChannel.assertNoFramesReceived() @@ -455,7 +466,7 @@ class ConfiguringPipelineWithFramePayloadStreamsTests: XCTestCase { } let serverRecorder = HTTP1ServerRequestRecorderHandler() XCTAssertNoThrow(try self.clientChannel.pipeline.addHTTPClientHandlers().wait()) - + XCTAssertNoThrow(try self.serverChannel.configureCommonHTTPServerPipeline(h2ConnectionChannelConfigurator: { $0.pipeline.addHandler(ErrorHandler()) }) { channel in return channel.pipeline.addHandler(serverRecorder) }.wait()) @@ -472,19 +483,21 @@ class ConfiguringPipelineWithFramePayloadStreamsTests: XCTestCase { XCTAssertNoThrow(try requestPromise.futureResult.wait()) self.interactInMemory(self.clientChannel, self.serverChannel) - + // Assert that the user-provided handler received the // HTTP1 parts corresponding to the H2 message sent - XCTAssertEqual(2, serverRecorder.receivedParts.count) - if case .some(.head(let head)) = serverRecorder.receivedParts.first { - XCTAssertEqual(.GET, head.method) - XCTAssertEqual("/testHTTP1", head.uri) - } else { - XCTFail("Expected head") - } - if case .some(.end(_)) = serverRecorder.receivedParts.last { - } else { - XCTFail("Expected end") + serverRecorder.receivedParts.withLockedValue { receivedParts in + XCTAssertEqual(2, receivedParts.count) + if case .some(.head(let head)) = receivedParts.first { + XCTAssertEqual(.GET, head.method) + XCTAssertEqual("/testHTTP1", head.uri) + } else { + XCTFail("Expected head") + } + if case .some(.end(_)) = receivedParts.last { + } else { + XCTFail("Expected end") + } } self.clientChannel.assertNoFramesReceived() self.serverChannel.assertNoFramesReceived() diff --git a/Tests/NIOHTTP2Tests/HTTP2FramePayloadStreamMultiplexerTests.swift b/Tests/NIOHTTP2Tests/HTTP2FramePayloadStreamMultiplexerTests.swift index a041568..db9a41a 100644 --- a/Tests/NIOHTTP2Tests/HTTP2FramePayloadStreamMultiplexerTests.swift +++ b/Tests/NIOHTTP2Tests/HTTP2FramePayloadStreamMultiplexerTests.swift @@ -91,9 +91,9 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { } func testHeadersFramesCreateNewChannels() throws { - var channelCount = 0 + let channelCount = ManagedAtomic(0) let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in - channelCount += 1 + channelCount.wrappingIncrement(ordering: .sequentiallyConsistent) return channel.close() } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -104,16 +104,14 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.writeInbound(frame)) } - XCTAssertEqual(channelCount, 50) + XCTAssertEqual(channelCount.load(ordering: .sequentiallyConsistent), 50) XCTAssertNoThrow(try self.channel.finish()) } func testChannelsCloseThemselvesWhenToldTo() throws { - var completedChannelCount = 0 - var closeFutures: [EventLoopFuture] = [] + let completedChannelCount = ManagedAtomic(0) let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in - closeFutures.append(channel.closeFuture) - channel.closeFuture.whenSuccess { completedChannelCount += 1 } + channel.closeFuture.whenSuccess { completedChannelCount.wrappingIncrement(ordering: .sequentiallyConsistent) } return channel.eventLoop.makeSucceededFuture(()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -124,7 +122,7 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders(), endStream: true))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) } - XCTAssertEqual(completedChannelCount, 0) + XCTAssertEqual(completedChannelCount.load(ordering: .sequentiallyConsistent), 0) // Now we send them all a clean exit. for streamID in streamIDs { @@ -134,12 +132,12 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { (self.channel.eventLoop as! EmbeddedEventLoop).run() // At this stage all the promises should be completed. - XCTAssertEqual(completedChannelCount, 50) + XCTAssertEqual(completedChannelCount.load(ordering: .sequentiallyConsistent), 50) XCTAssertNoThrow(try self.channel.finish()) } func testChannelsCloseAfterResetStreamFrameFirstThenEvent() throws { - var closeError: Error? = nil + let closeError = NIOLockedValueBox(nil) XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) @@ -149,8 +147,14 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { let rstStreamFrame = HTTP2Frame(streamID: streamID, payload: .rstStream(.cancel)) let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in - XCTAssertNil(closeError) - channel.closeFuture.whenFailure { closeError = $0 } + closeError.withLockedValue { closeError in + XCTAssertNil(closeError) + } + channel.closeFuture.whenFailure { error in + closeError.withLockedValue { closeError in + closeError = error + } + } return channel.pipeline.addHandler(FramePayloadExpecter(expectedPayload: [frame.payload, rstStreamFrame.payload])) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -158,7 +162,9 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { // Let's open the stream up. XCTAssertNoThrow(try self.channel.writeInbound(frame)) self.activateStream(streamID) - XCTAssertNil(closeError) + closeError.withLockedValue { closeError in + XCTAssertNil(closeError) + } // Now we can send a RST_STREAM frame. XCTAssertNoThrow(try self.channel.writeInbound(rstStreamFrame)) @@ -169,13 +175,15 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { (self.channel.eventLoop as! EmbeddedEventLoop).run() // At this stage the stream should be closed with the appropriate error code. - XCTAssertEqual(closeError as? NIOHTTP2Errors.StreamClosed, - NIOHTTP2Errors.streamClosed(streamID: streamID, errorCode: .cancel)) + closeError.withLockedValue { closeError in + XCTAssertEqual(closeError as? NIOHTTP2Errors.StreamClosed, + NIOHTTP2Errors.streamClosed(streamID: streamID, errorCode: .cancel)) + } XCTAssertNoThrow(try self.channel.finish()) } func testChannelsCloseAfterGoawayFrameFirstThenEvent() throws { - var closeError: Error? = nil + let closeError = NIOLockedValueBox(nil) XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) @@ -185,8 +193,14 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { let goAwayFrame = HTTP2Frame(streamID: .rootStream, payload: .goAway(lastStreamID: .rootStream, errorCode: .http11Required, opaqueData: nil)) let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in - XCTAssertNil(closeError) - channel.closeFuture.whenFailure { closeError = $0 } + closeError.withLockedValue { closeError in + XCTAssertNil(closeError) + } + channel.closeFuture.whenFailure { error in + closeError.withLockedValue { closeError in + closeError = error + } + } // The channel won't see the goaway frame. return channel.pipeline.addHandler(FramePayloadExpecter(expectedPayload: [frame.payload])) } @@ -195,7 +209,9 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { // Let's open the stream up. XCTAssertNoThrow(try self.channel.writeInbound(frame)) self.activateStream(streamID) - XCTAssertNil(closeError) + closeError.withLockedValue { closeError in + XCTAssertNil(closeError) + } // Now we can send a GOAWAY frame. This will close the stream. XCTAssertNoThrow(try self.channel.writeInbound(goAwayFrame)) @@ -206,8 +222,10 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { (self.channel.eventLoop as! EmbeddedEventLoop).run() // At this stage the stream should be closed with the appropriate manufactured error code. - XCTAssertEqual(closeError as? NIOHTTP2Errors.StreamClosed, - NIOHTTP2Errors.streamClosed(streamID: streamID, errorCode: .refusedStream)) + closeError.withLockedValue { closeError in + XCTAssertEqual(closeError as? NIOHTTP2Errors.StreamClosed, + NIOHTTP2Errors.streamClosed(streamID: streamID, errorCode: .refusedStream)) + } XCTAssertNoThrow(try self.channel.finish()) } @@ -333,16 +351,18 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { 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 } + let closed = ManagedAtomic(false) + childChannel.close().whenComplete { _ in + closed.store(true, ordering: .sequentiallyConsistent) + } XCTAssertEqual(frameReceiver.flushedWrites.count, 1) frameReceiver.flushedWrites[0].assertRstStreamFrame(streamID: streamID, errorCode: .cancel) - XCTAssertFalse(closed) + XCTAssertFalse(closed.load(ordering: .sequentiallyConsistent)) // Now send the stream closed event. This will satisfy the close promise. let userEvent = StreamClosedEvent(streamID: streamID, reason: .cancel) self.channel.pipeline.fireUserInboundEventTriggered(userEvent) - XCTAssertTrue(closed) + XCTAssertTrue(closed.load(ordering: .sequentiallyConsistent)) XCTAssertNoThrow(try self.channel.finish()) } @@ -371,35 +391,35 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { 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 + let firstClosed = ManagedAtomic(false) + let secondClosed = ManagedAtomic(false) + let thirdClosed = ManagedAtomic(false) childChannel.close().whenComplete { _ in - XCTAssertFalse(firstClosed) - XCTAssertFalse(secondClosed) - XCTAssertFalse(thirdClosed) - firstClosed = true + XCTAssertFalse(firstClosed.load(ordering: .sequentiallyConsistent)) + XCTAssertFalse(secondClosed.load(ordering: .sequentiallyConsistent)) + XCTAssertFalse(thirdClosed.load(ordering: .sequentiallyConsistent)) + firstClosed.store(true, ordering: .sequentiallyConsistent) } childChannel.close().whenComplete { _ in - XCTAssertTrue(firstClosed) - XCTAssertFalse(secondClosed) - XCTAssertFalse(thirdClosed) - secondClosed = true + XCTAssertTrue(firstClosed.load(ordering: .sequentiallyConsistent)) + XCTAssertFalse(secondClosed.load(ordering: .sequentiallyConsistent)) + XCTAssertFalse(thirdClosed.load(ordering: .sequentiallyConsistent)) + secondClosed.store(true, ordering: .sequentiallyConsistent) } childChannel.close().whenComplete { _ in - XCTAssertTrue(firstClosed) - XCTAssertTrue(secondClosed) - XCTAssertFalse(thirdClosed) - thirdClosed = true + XCTAssertTrue(firstClosed.load(ordering: .sequentiallyConsistent)) + XCTAssertTrue(secondClosed.load(ordering: .sequentiallyConsistent)) + XCTAssertFalse(thirdClosed.load(ordering: .sequentiallyConsistent)) + thirdClosed.store(true, ordering: .sequentiallyConsistent) } XCTAssertEqual(frameReceiver.flushedWrites.count, 1) frameReceiver.flushedWrites[0].assertRstStreamFrame(streamID: streamID, errorCode: .cancel) - XCTAssertFalse(thirdClosed) + XCTAssertFalse(thirdClosed.load(ordering: .sequentiallyConsistent)) // Now send the stream closed event. This will satisfy the close promise. let userEvent = StreamClosedEvent(streamID: streamID, reason: .cancel) self.channel.pipeline.fireUserInboundEventTriggered(userEvent) - XCTAssertTrue(thirdClosed) + XCTAssertTrue(thirdClosed.load(ordering: .sequentiallyConsistent)) XCTAssertNoThrow(try self.channel.finish()) } @@ -427,16 +447,24 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { 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 } + let closeError = NIOLockedValueBox(nil) + childChannel.close().whenFailure { error in + closeError.withLockedValue { closeError in + closeError = error + } + } XCTAssertEqual(frameReceiver.flushedWrites.count, 1) frameReceiver.flushedWrites[0].assertRstStreamFrame(streamID: streamID, errorCode: .cancel) - XCTAssertNil(closeError) + closeError.withLockedValue { closeError in + XCTAssertNil(closeError) + } // Now send the stream closed event. This will fail the close promise. let userEvent = StreamClosedEvent(streamID: streamID, reason: .cancel) self.channel.pipeline.fireUserInboundEventTriggered(userEvent) - XCTAssertEqual(closeError as? NIOHTTP2Errors.StreamClosed, NIOHTTP2Errors.streamClosed(streamID: streamID, errorCode: .cancel)) + closeError.withLockedValue { closeError in + XCTAssertEqual(closeError as? NIOHTTP2Errors.StreamClosed, NIOHTTP2Errors.streamClosed(streamID: streamID, errorCode: .cancel)) + } XCTAssertNoThrow(try self.channel.finish()) } @@ -530,10 +558,10 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { // 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 } + let channelClosed = ManagedAtomic(false) + childChannel.closeFuture.whenComplete { _ in channelClosed.store(true, ordering: .sequentiallyConsistent) } XCTAssertEqual(writeRecorder.flushedWrites.count, 0) - XCTAssertFalse(channelClosed) + XCTAssertFalse(channelClosed.load(ordering: .sequentiallyConsistent)) setupCompletePromise.fail(MyError()) self.channel.assertNoFramesReceived() @@ -553,19 +581,19 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { XCTAssertEqual(frameRecorder.receivedFrames.count, 0) XCTAssertFalse(childChannel.isActive) XCTAssertEqual(writeRecorder.flushedWrites.count, 1) - XCTAssertFalse(channelClosed) + XCTAssertFalse(channelClosed.load(ordering: .sequentiallyConsistent)) (childChannel.eventLoop as! EmbeddedEventLoop).run() - XCTAssertTrue(channelClosed) + XCTAssertTrue(channelClosed.load(ordering: .sequentiallyConsistent)) XCTAssertNoThrow(try self.channel.finish()) } - func testFlushingOneChannelDoesntFlushThemAll() throws { + func testFlushingOneChannelDoesntFlushThemAll() async throws { let writeTracker = FrameWriteRecorder() - var channels: [Channel] = [] + let (channelsStream, channelsContinuation) = AsyncStream.makeStream(of: Channel.self) let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in - channels.append(channel) + channelsContinuation.yield(channel) return channel.eventLoop.makeSucceededFuture(()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(writeTracker).wait()) @@ -581,32 +609,34 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.writeInbound(frame)) self.activateStream(streamID) } - XCTAssertEqual(channels.count, 2) + var streamChannelIterator = channelsStream.makeAsyncIterator() + let firstStreamChannel = await streamChannelIterator.next()! + let secondStreamChannel = await streamChannelIterator.next()! // 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() { + for channel in [firstStreamChannel, secondStreamChannel] { let frame = HTTP2Frame.FramePayload.headers(.init(headers: HPACKHeaders())) - channels[idx].write(frame, promise: nil) + channel.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[0].flush() + firstStreamChannel.flush() XCTAssertEqual(writeTracker.flushedWrites.count, 1) // Now the other. - channels[1].flush() + secondStreamChannel.flush() XCTAssertEqual(writeTracker.flushedWrites.count, 2) XCTAssertNoThrow(try self.channel.finish()) } func testUnflushedWritesFailOnClose() throws { - var childChannel: Channel? = nil + let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in - childChannel = channel + childChannelPromise.succeed(channel) return channel.eventLoop.makeSucceededFuture(()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -617,26 +647,34 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.writeInbound(frame)) XCTAssertNotNil(channel) + let childChannel = try childChannelPromise.futureResult.wait() + // We will now write a headers frame to the channel, but don't flush it. - var writeError: Error? = nil + let writeError = NIOLockedValueBox(nil) let responseFrame = HTTP2Frame.FramePayload.headers(.init(headers: HPACKHeaders())) - childChannel!.write(responseFrame).whenFailure { - writeError = $0 + childChannel.write(responseFrame).whenFailure { error in + writeError.withLockedValue { writeError in + writeError = error + } + } + writeError.withLockedValue { writeError in + XCTAssertNil(writeError) } - XCTAssertNil(writeError) // Now we're going to deliver a normal close to the stream. let userEvent = StreamClosedEvent(streamID: streamID, reason: nil) self.channel.pipeline.fireUserInboundEventTriggered(userEvent) - XCTAssertEqual(writeError as? ChannelError, ChannelError.eof) + writeError.withLockedValue { writeError in + XCTAssertEqual(writeError as? ChannelError, ChannelError.eof) + } XCTAssertNoThrow(try self.channel.finish()) } func testUnflushedWritesFailOnError() throws { - var childChannel: Channel? = nil + let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in - childChannel = channel + childChannelPromise.succeed(channel) return channel.eventLoop.makeSucceededFuture(()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -647,26 +685,35 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.writeInbound(frame)) XCTAssertNotNil(channel) + let childChannel = try childChannelPromise.futureResult.wait() + // We will now write a headers frame to the channel, but don't flush it. - var writeError: Error? = nil + let writeError = NIOLockedValueBox(nil) let responseFrame = HTTP2Frame.FramePayload.headers(.init(headers: HPACKHeaders())) - childChannel!.write(responseFrame).whenFailure { - writeError = $0 + childChannel.write(responseFrame).whenFailure { error in + writeError.withLockedValue { writeError in + writeError = error + } + } + writeError.withLockedValue { writeError in + XCTAssertNil(writeError) } - XCTAssertNil(writeError) // Now we're going to deliver a normal close to the stream. let userEvent = StreamClosedEvent(streamID: streamID, reason: .cancel) self.channel.pipeline.fireUserInboundEventTriggered(userEvent) - XCTAssertEqual(writeError as? NIOHTTP2Errors.StreamClosed, NIOHTTP2Errors.streamClosed(streamID: streamID, errorCode: .cancel)) + + writeError.withLockedValue { writeError in + XCTAssertEqual(writeError as? NIOHTTP2Errors.StreamClosed, NIOHTTP2Errors.streamClosed(streamID: streamID, errorCode: .cancel)) + } XCTAssertNoThrow(try self.channel.finish()) } func testWritesFailOnClosedStreamChannels() throws { - var childChannel: Channel? = nil + let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in - childChannel = channel + childChannelPromise.succeed(channel) return channel.eventLoop.makeSucceededFuture(()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -681,22 +728,28 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { let userEvent = StreamClosedEvent(streamID: streamID, reason: nil) self.channel.pipeline.fireUserInboundEventTriggered(userEvent) + let childChannel = try childChannelPromise.futureResult.wait() + // We will now write a headers frame to the channel. This should fail immediately. - var writeError: Error? = nil + let writeError = NIOLockedValueBox(nil) let responseFrame = HTTP2Frame.FramePayload.headers(.init(headers: HPACKHeaders())) - childChannel!.write(responseFrame).whenFailure { - writeError = $0 + childChannel.write(responseFrame).whenFailure { error in + writeError.withLockedValue { writeError in + writeError = error + } + } + writeError.withLockedValue { writeError in + XCTAssertEqual(writeError as? ChannelError, ChannelError.ioOnClosedChannel) } - XCTAssertEqual(writeError as? ChannelError, ChannelError.ioOnClosedChannel) XCTAssertNoThrow(try self.channel.finish()) } func testReadPullsInAllFrames() throws { - var childChannel: Channel? = nil + let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) let frameRecorder = InboundFramePayloadRecorder() let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel -> EventLoopFuture in - childChannel = channel + childChannelPromise.succeed(channel) // We're going to disable autoRead on this channel. return channel.getOption(ChannelOptions.autoRead).map { @@ -721,7 +774,8 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders()))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) self.activateStream(1) - XCTAssertNotNil(childChannel) + + let childChannel = try childChannelPromise.futureResult.wait() // Now we're going to deliver 5 data frames for this stream. var buffer = self.channel.allocator.buffer(capacity: 12) @@ -735,7 +789,7 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { XCTAssertEqual(frameRecorder.receivedFrames.count, 0) // We'll call read() on the child channel. - childChannel!.read() + childChannel.read() // All frames should now have been delivered. XCTAssertEqual(frameRecorder.receivedFrames.count, 6) @@ -747,27 +801,22 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.finish()) } - func testReadIsPerChannel() throws { + func testReadIsPerChannel() async 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. - var expectedStreamID = 1 - var autoRead = false - var frameRecorders: [HTTP2StreamID: InboundFramePayloadRecorder] = [:] + let autoRead = ManagedAtomic(false) + let (channelsStream, channelsContinuation) = AsyncStream.makeStream(of: Channel.self) let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel -> EventLoopFuture in - let recorder = InboundFramePayloadRecorder() - frameRecorders[HTTP2StreamID(expectedStreamID)] = recorder - expectedStreamID += 2 - + channelsContinuation.yield(channel) // We'll disable auto read on the first channel only. - let autoReadValue = autoRead - autoRead = true + let autoReadValue = autoRead.exchange(true, ordering: .sequentiallyConsistent) return channel.setOption(ChannelOptions.autoRead, value: autoReadValue).flatMap { - channel.pipeline.addHandler(recorder) + channel.pipeline.addHandler(InboundFramePayloadRecorder()) } } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -780,11 +829,17 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.writeInbound(frame)) self.activateStream(streamID) } - XCTAssertEqual(frameRecorders.count, 2) + var streamChannelIterator = channelsStream.makeAsyncIterator() + let firstStreamChannel = await streamChannelIterator.next()! + let secondStreamChannel = await streamChannelIterator.next()! // Stream 1 should not have received a frame, stream 3 should. - XCTAssertEqual(frameRecorders[firstStreamID]!.receivedFrames.count, 0) - XCTAssertEqual(frameRecorders[secondStreamID]!.receivedFrames.count, 1) + try await firstStreamChannel.pipeline.handler(type: InboundFramePayloadRecorder.self).map { recorder in + XCTAssertEqual(recorder.receivedFrames.count, 0) + }.get() + try await secondStreamChannel.pipeline.handler(type: InboundFramePayloadRecorder.self).map { recorder in + XCTAssertEqual(recorder.receivedFrames.count, 1) + }.get() // Deliver a DATA frame to each stream, which should also have gone into stream 3 but not stream 1. var buffer = self.channel.allocator.buffer(capacity: 12) @@ -795,21 +850,25 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { } // Stream 1 should not have received a frame, stream 3 should. - XCTAssertEqual(frameRecorders[firstStreamID]!.receivedFrames.count, 0) - XCTAssertEqual(frameRecorders[secondStreamID]!.receivedFrames.count, 2) + try await firstStreamChannel.pipeline.handler(type: InboundFramePayloadRecorder.self).map { recorder in + XCTAssertEqual(recorder.receivedFrames.count, 0) + }.get() + try await secondStreamChannel.pipeline.handler(type: InboundFramePayloadRecorder.self).map { recorder in + XCTAssertEqual(recorder.receivedFrames.count, 2) + }.get() XCTAssertNoThrow(try self.channel.finish()) } func testReadWillCauseAutomaticFrameDelivery() throws { - var childChannel: Channel? = nil + let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) let frameRecorder = InboundFramePayloadRecorder() let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel -> EventLoopFuture in - childChannel = channel + childChannelPromise.succeed(channel) // We're going to disable autoRead on this channel. return channel.setOption(ChannelOptions.autoRead, value: false).flatMap { - channel.pipeline.addHandler(frameRecorder) + return channel.pipeline.addHandler(frameRecorder) } } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -821,17 +880,21 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders()))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) self.activateStream(streamID) + + (self.channel.eventLoop as! EmbeddedEventLoop).run() + let childChannel = try childChannelPromise.futureResult.wait() + XCTAssertNotNil(childChannel) // This stream should have seen no frames. XCTAssertEqual(frameRecorder.receivedFrames.count, 0) // Call read, the header frame will come through. - childChannel!.read() + childChannel.read() XCTAssertEqual(frameRecorder.receivedFrames.count, 1) // Call read again, nothing happens. - childChannel!.read() + childChannel.read() XCTAssertEqual(frameRecorder.receivedFrames.count, 1) // Now deliver a data frame. @@ -851,11 +914,11 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { } func testReadWithNoPendingDataCausesReadOnParentChannel() throws { - var childChannel: Channel? = nil + let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) let readCounter = ReadCounter() let frameRecorder = InboundFramePayloadRecorder() let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel -> EventLoopFuture in - childChannel = channel + childChannelPromise.succeed(channel) // We're going to disable autoRead on this channel. return channel.setOption(ChannelOptions.autoRead, value: false).flatMap { @@ -872,23 +935,31 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders()))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) self.activateStream(streamID) - XCTAssertNotNil(childChannel) + + let childChannel = try childChannelPromise.futureResult.wait() // This stream should have seen no frames. XCTAssertEqual(frameRecorder.receivedFrames.count, 0) // There should be no calls to read. - XCTAssertEqual(readCounter.readCount, 0) + readCounter.readCount.withLockedValue { readCount in + XCTAssertEqual(readCount, 0) + } // Call read, the header frame will come through. No calls to read on the parent stream. - childChannel!.read() + childChannel.read() + XCTAssertEqual(frameRecorder.receivedFrames.count, 1) - XCTAssertEqual(readCounter.readCount, 0) + readCounter.readCount.withLockedValue { readCount in + XCTAssertEqual(readCount, 0) + } // Call read again, read is called on the parent stream. No frames delivered. - childChannel!.read() + childChannel.read() XCTAssertEqual(frameRecorder.receivedFrames.count, 1) - XCTAssertEqual(readCounter.readCount, 1) + readCounter.readCount.withLockedValue { readCount in + XCTAssertEqual(readCount, 1) + } // Now deliver a data frame. var buffer = self.channel.allocator.buffer(capacity: 12) @@ -898,32 +969,40 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { // This frame should have been immediately delivered. No extra call to read. XCTAssertEqual(frameRecorder.receivedFrames.count, 2) - XCTAssertEqual(readCounter.readCount, 1) + readCounter.readCount.withLockedValue { readCount in + XCTAssertEqual(readCount, 1) + } // Another call to read issues a read to the parent stream. - childChannel!.read() + childChannel.read() XCTAssertEqual(frameRecorder.receivedFrames.count, 2) - XCTAssertEqual(readCounter.readCount, 2) + readCounter.readCount.withLockedValue { readCount in + XCTAssertEqual(readCount, 2) + } // Another call to read, this time does not issue a read to the parent stream. - childChannel!.read() + childChannel.read() XCTAssertEqual(frameRecorder.receivedFrames.count, 2) - XCTAssertEqual(readCounter.readCount, 2) + readCounter.readCount.withLockedValue { readCount in + XCTAssertEqual(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) + readCounter.readCount.withLockedValue { readCount in + XCTAssertEqual(readCount, 2) + } XCTAssertNoThrow(try self.channel.finish()) } func testHandlersAreRemovedOnClosure() throws { - var handlerRemoved = false + let handlerRemoved = ManagedAtomic(false) let handlerRemovedPromise: EventLoopPromise = self.channel.eventLoop.makePromise() - handlerRemovedPromise.futureResult.whenComplete { _ in handlerRemoved = true } + handlerRemovedPromise.futureResult.whenComplete { _ in handlerRemoved.store(true, ordering: .sequentiallyConsistent) } let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in return channel.pipeline.addHandler(HandlerRemovedHandler(removedPromise: handlerRemovedPromise)) @@ -936,24 +1015,24 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.writeInbound(frame)) // No handlerRemoved so far. - XCTAssertFalse(handlerRemoved) + XCTAssertFalse(handlerRemoved.load(ordering: .sequentiallyConsistent)) // Now we send the channel a clean exit. let event = StreamClosedEvent(streamID: streamID, reason: nil) self.channel.pipeline.fireUserInboundEventTriggered(event) - XCTAssertFalse(handlerRemoved) + XCTAssertFalse(handlerRemoved.load(ordering: .sequentiallyConsistent)) // The handlers will only be removed after we spin the loop. (self.channel.eventLoop as! EmbeddedEventLoop).run() - XCTAssertTrue(handlerRemoved) + XCTAssertTrue(handlerRemoved.load(ordering: .sequentiallyConsistent)) XCTAssertNoThrow(try self.channel.finish()) } func testHandlersAreRemovedOnClosureWithError() throws { - var handlerRemoved = false + let handlerRemoved = ManagedAtomic(false) let handlerRemovedPromise: EventLoopPromise = self.channel.eventLoop.makePromise() - handlerRemovedPromise.futureResult.whenComplete { _ in handlerRemoved = true } + handlerRemovedPromise.futureResult.whenComplete { _ in handlerRemoved.store(true, ordering: .sequentiallyConsistent) } let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in return channel.pipeline.addHandler(HandlerRemovedHandler(removedPromise: handlerRemovedPromise)) @@ -966,16 +1045,16 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.writeInbound(frame)) // No handlerRemoved so far. - XCTAssertFalse(handlerRemoved) + XCTAssertFalse(handlerRemoved.load(ordering: .sequentiallyConsistent)) // Now we send the channel a clean exit. let event = StreamClosedEvent(streamID: streamID, reason: .cancel) self.channel.pipeline.fireUserInboundEventTriggered(event) - XCTAssertFalse(handlerRemoved) + XCTAssertFalse(handlerRemoved.load(ordering: .sequentiallyConsistent)) // The handlers will only be removed after we spin the loop. (self.channel.eventLoop as! EmbeddedEventLoop).run() - XCTAssertTrue(handlerRemoved) + XCTAssertTrue(handlerRemoved.load(ordering: .sequentiallyConsistent)) XCTAssertNoThrow(try self.channel.finish()) } @@ -985,7 +1064,7 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { let createdChannelCount = ManagedAtomic(0) let configuredChannelCount = ManagedAtomic(0) let streamIDs = NIOLockedValueBox(Array()) - let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in + let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in XCTFail("Must not be called") return channel.eventLoop.makeFailedFuture(MyError()) } @@ -995,11 +1074,11 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { for _ in 0..<3 { let channelPromise: EventLoopPromise = self.channel.eventLoop.makePromise() multiplexer.createStreamChannel(promise: channelPromise) { channel in - _ = createdChannelCount.loadThenWrappingIncrement(ordering: .sequentiallyConsistent) + createdChannelCount.wrappingIncrement(ordering: .sequentiallyConsistent) return configurePromise.futureResult } channelPromise.futureResult.whenSuccess { channel in - _ = configuredChannelCount.loadThenWrappingIncrement(ordering: .sequentiallyConsistent) + configuredChannelCount.wrappingIncrement(ordering: .sequentiallyConsistent) // Write some headers: the flush will trigger a stream ID to be assigned to the channel. channel.writeAndFlush(HTTP2Frame.FramePayload.headers(.init(headers: [:]))).whenSuccess { channel.getOption(HTTP2StreamChannelOptions.streamID).whenSuccess { streamID in @@ -1045,11 +1124,11 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { for _ in 0..<3 { let channelPromise: EventLoopPromise = self.channel.eventLoop.makePromise() multiplexer.createStreamChannel(promise: channelPromise) { channel in - _ = createdChannelCount.loadThenWrappingIncrement(ordering: .sequentiallyConsistent) + createdChannelCount.wrappingIncrement(ordering: .sequentiallyConsistent) return configurePromise.futureResult } channelPromise.futureResult.whenSuccess { channel in - _ = configuredChannelCount.loadThenWrappingIncrement(ordering: .sequentiallyConsistent) + configuredChannelCount.wrappingIncrement(ordering: .sequentiallyConsistent) // Write some headers: the flush will trigger a stream ID to be assigned to the channel. channel.writeAndFlush(HTTP2Frame.FramePayload.headers(.init(headers: [:]))).whenSuccess { channel.getOption(HTTP2StreamChannelOptions.streamID).whenSuccess { streamID in @@ -1087,7 +1166,7 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) - let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in + let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in XCTFail("Must not be called") return channel.eventLoop.makeFailedFuture(MyError()) } @@ -1116,7 +1195,7 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { let configurePromise: EventLoopPromise = self.channel.eventLoop.makePromise() let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) - let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in + let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in XCTFail("Must not be called") return channel.eventLoop.makeFailedFuture(MyError()) } @@ -1153,9 +1232,9 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { let configurePromise: EventLoopPromise = self.channel.eventLoop.makePromise() let writeRecorder = FrameWriteRecorder() - let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { _ in + let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) + return channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(writeRecorder).wait()) XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -1171,59 +1250,59 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { } func testCreatedChildChannelDoesNotActivateEarly() throws { - var activated = false + let activated = ManagedAtomic(false) let activePromise: EventLoopPromise = self.channel.eventLoop.makePromise() - let activeRecorder = ActiveHandler(activatedPromise: activePromise) activePromise.futureResult.map { - activated = true + activated.store(true, ordering: .sequentiallyConsistent) }.whenFailure { (_: Error) in XCTFail("Activation promise must not fail") } - let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { _ in + let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) + return channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) multiplexer.createStreamChannel(promise: nil) { channel in + let activeRecorder = ActiveHandler(activatedPromise: activePromise) return channel.pipeline.addHandler(activeRecorder) } (self.channel.eventLoop as! EmbeddedEventLoop).run() - XCTAssertFalse(activated) + XCTAssertFalse(activated.load(ordering: .sequentiallyConsistent)) XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) - XCTAssertTrue(activated) + XCTAssertTrue(activated.load(ordering: .sequentiallyConsistent)) XCTAssertNoThrow(try self.channel.finish()) } func testCreatedChildChannelActivatesIfParentIsActive() throws { - var activated = false + let activated = ManagedAtomic(false) let activePromise: EventLoopPromise = self.channel.eventLoop.makePromise() - let activeRecorder = ActiveHandler(activatedPromise: activePromise) activePromise.futureResult.map { - activated = true + activated.store(true, ordering: .sequentiallyConsistent) }.whenFailure { (_: Error) in XCTFail("Activation promise must not fail") } - let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { _ in + let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) + return channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 8765)).wait()) - XCTAssertFalse(activated) + XCTAssertFalse(activated.load(ordering: .sequentiallyConsistent)) multiplexer.createStreamChannel(promise: nil) { channel in + let activeRecorder = ActiveHandler(activatedPromise: activePromise) return channel.pipeline.addHandler(activeRecorder) } (self.channel.eventLoop as! EmbeddedEventLoop).run() - XCTAssertTrue(activated) + XCTAssertTrue(activated.load(ordering: .sequentiallyConsistent)) XCTAssertNoThrow(try self.channel.finish()) } @@ -1231,28 +1310,28 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { func testInitiatedChildChannelActivates() throws { XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) - var activated = false + let activated = ManagedAtomic(false) let activePromise: EventLoopPromise = self.channel.eventLoop.makePromise() - let activeRecorder = ActiveHandler(activatedPromise: activePromise) activePromise.futureResult.map { - activated = true + activated.store(true, ordering: .sequentiallyConsistent) }.whenFailure { (_: Error) in XCTFail("Activation promise must not fail") } let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in + let activeRecorder = ActiveHandler(activatedPromise: activePromise) return channel.pipeline.addHandler(activeRecorder) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) self.channel.pipeline.fireChannelActive() // Open a new stream. - XCTAssertFalse(activated) + XCTAssertFalse(activated.load(ordering: .sequentiallyConsistent)) let streamID = HTTP2StreamID(1) let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders()))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) - XCTAssertTrue(activated) + XCTAssertTrue(activated.load(ordering: .sequentiallyConsistent)) XCTAssertNoThrow(try self.channel.finish()) } @@ -1270,15 +1349,15 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { func testMultiplexerForwardsActiveToParent() throws { self.channel.addNoOpMultiplexer(mode: .client) - var didActivate = false + let activated = ManagedAtomic(false) let activePromise = self.channel.eventLoop.makePromise(of: Void.self) activePromise.futureResult.whenSuccess { - didActivate = true + activated.store(true, ordering: .sequentiallyConsistent) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(ActiveHandler(activatedPromise: activePromise)).wait()) XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/nothing")).wait()) - XCTAssertTrue(didActivate) + XCTAssertTrue(activated.load(ordering: .sequentiallyConsistent)) XCTAssertNoThrow(try self.channel.finish()) } @@ -1305,11 +1384,11 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { } func testCreatedChildChannelCanBeClosedBeforeWritingHeaders() throws { - var closed = false + let closed = ManagedAtomic(false) let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.channel) { channel in XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) + return channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -1320,12 +1399,14 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { self.channel.embeddedEventLoop.run() let child = try assertNoThrowWithValue(channelPromise.futureResult.wait()) - child.closeFuture.whenComplete { _ in closed = true } + child.closeFuture.whenComplete { _ in + closed.store(true, ordering: .sequentiallyConsistent) + } - XCTAssertFalse(closed) + XCTAssertFalse(closed.load(ordering: .sequentiallyConsistent)) child.close(promise: nil) self.channel.embeddedEventLoop.run() - XCTAssertTrue(closed) + XCTAssertTrue(closed.load(ordering: .sequentiallyConsistent)) XCTAssertNoThrow(XCTAssertTrue(try self.channel.finish().isClean)) } @@ -1354,14 +1435,14 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { } func testCreatedChildChannelCanBeClosedBeforeWritingHeadersWhenBaseIsActive() throws { - var closed = false + 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 multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.channel) { channel in XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) + return channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -1372,12 +1453,14 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { self.channel.embeddedEventLoop.run() let child = try assertNoThrowWithValue(channelPromise.futureResult.wait()) - child.closeFuture.whenComplete { _ in closed = true } + child.closeFuture.whenComplete { _ in + closed.store(true, ordering: .sequentiallyConsistent) + } - XCTAssertFalse(closed) + XCTAssertFalse(closed.load(ordering: .sequentiallyConsistent)) child.close(promise: nil) self.channel.embeddedEventLoop.run() - XCTAssertTrue(closed) + XCTAssertTrue(closed.load(ordering: .sequentiallyConsistent)) XCTAssertNoThrow(XCTAssertTrue(try self.channel.finish().isClean)) } @@ -1429,7 +1512,9 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) XCTAssertEqual(frameRecorder.receivedFrames.count, 0) - XCTAssertEqual(readCompleteCounter.readCompleteCount, 0) + readCompleteCounter.readCompleteCount.withLockedValue { readCompleteCount in + XCTAssertEqual(readCompleteCount, 0) + } // Wake up and activate the stream. let requestHeaders = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) @@ -1439,7 +1524,9 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { self.channel.embeddedEventLoop.run() XCTAssertEqual(frameRecorder.receivedFrames.count, 1) - XCTAssertEqual(readCompleteCounter.readCompleteCount, 1) + readCompleteCounter.readCompleteCount.withLockedValue { readCompleteCount in + XCTAssertEqual(readCompleteCount, 1) + } // Now we're going to send 9 data frames. var requestData = self.channel.allocator.buffer(capacity: 1024) @@ -1452,19 +1539,25 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { // We should have 1 read (the HEADERS), and one read complete. XCTAssertEqual(frameRecorder.receivedFrames.count, 1) - XCTAssertEqual(readCompleteCounter.readCompleteCount, 1) + readCompleteCounter.readCompleteCount.withLockedValue { readCompleteCount in + XCTAssertEqual(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) + readCompleteCounter.readCompleteCount.withLockedValue { readCompleteCount in + XCTAssertEqual(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) + readCompleteCounter.readCompleteCount.withLockedValue { readCompleteCount in + XCTAssertEqual(readCompleteCount, 2) + } } func testMultiplexerCorrectlyTellsAllStreamsAboutReadComplete() { @@ -1484,7 +1577,9 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) XCTAssertEqual(frameRecorder.receivedFrames.count, 0) - XCTAssertEqual(readCompleteCounter.readCompleteCount, 0) + readCompleteCounter.readCompleteCount.withLockedValue { readCompleteCount in + XCTAssertEqual(readCompleteCount, 0) + } // Wake up and activate the streams. let requestHeaders = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) @@ -1497,12 +1592,16 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { self.channel.embeddedEventLoop.run() XCTAssertEqual(frameRecorder.receivedFrames.count, 3) - XCTAssertEqual(readCompleteCounter.readCompleteCount, 3) + readCompleteCounter.readCompleteCount.withLockedValue { readCompleteCount in + XCTAssertEqual(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) + readCompleteCounter.readCompleteCount.withLockedValue { readCompleteCount in + XCTAssertEqual(readCompleteCount, 3) + } // Now we're going to send a data frame on stream 1. var requestData = self.channel.allocator.buffer(capacity: 1024) @@ -1512,7 +1611,9 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { // 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) + readCompleteCounter.readCompleteCount.withLockedValue { readCompleteCount in + XCTAssertEqual(readCompleteCount, 3) + } // Fire read complete on the parent and it'll propagate to the child, but only to the one // that saw a frame. @@ -1520,21 +1621,25 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { // We should have 4 reads, and 4 read completes. XCTAssertEqual(frameRecorder.receivedFrames.count, 4) - XCTAssertEqual(readCompleteCounter.readCompleteCount, 4) + readCompleteCounter.readCompleteCount.withLockedValue { readCompleteCount in + XCTAssertEqual(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) + readCompleteCounter.readCompleteCount.withLockedValue { readCompleteCount in + XCTAssertEqual(readCompleteCount, 4) + } } func testMultiplexerModifiesStreamChannelWritabilityBasedOnFixedSizeTokens() throws { let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.channel, outboundBufferSizeHighWatermark: 100, - outboundBufferSizeLowWatermark: 50) { _ in + outboundBufferSizeLowWatermark: 50) { channel in XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) + return channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -1584,9 +1689,9 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { } func testMultiplexerModifiesStreamChannelWritabilityBasedOnParentChannelWritability() throws { - let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.channel) { _ in + let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.channel) { channel in XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) + return channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -1637,9 +1742,9 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.channel, outboundBufferSizeHighWatermark: 100, - outboundBufferSizeLowWatermark: 50) { _ in + outboundBufferSizeLowWatermark: 50) { channel in XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) + return channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -1706,9 +1811,9 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.channel, outboundBufferSizeHighWatermark: 100, - outboundBufferSizeLowWatermark: 50) { _ in + outboundBufferSizeLowWatermark: 50) { channel in XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) + return channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -1807,10 +1912,10 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { } func testReadWhenUsingAutoreadOnChildChannel() throws { - var childChannel: Channel? = nil + let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) let readCounter = ReadCounter() let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel -> EventLoopFuture in - childChannel = channel + childChannelPromise.succeed(channel) // We're going to _enable_ autoRead on this channel. return channel.setOption(ChannelOptions.autoRead, value: true).flatMap { @@ -1826,11 +1931,15 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders()))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) self.activateStream(streamID) - XCTAssertNotNil(childChannel) + + + _ = try childChannelPromise.futureResult.wait() // 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) + readCounter.readCount.withLockedValue { readCount in + XCTAssertEqual(readCount, 2) + } // Now deliver a data frame. var buffer = self.channel.allocator.buffer(capacity: 12) @@ -1839,12 +1948,16 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { 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) + readCounter.readCount.withLockedValue { readCount in + XCTAssertEqual(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) + readCounter.readCount.withLockedValue { readCount in + XCTAssertEqual(readCount, 5) + } XCTAssertNoThrow(try self.channel.finish()) } @@ -2003,11 +2116,15 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { let childChannel = try childChannelPromise.futureResult.wait() try childChannel.pipeline.handler(type: ErrorRecorder.self).map { errorRecorder in - XCTAssertEqual(errorRecorder.errors.count, 0) + errorRecorder.errors.withLockedValue { errors in + XCTAssertEqual(errors.count, 0) + } }.wait() let secondChildChannel = try secondChildChannelPromise.futureResult.wait() try secondChildChannel.pipeline.handler(type: ErrorRecorder.self).map { errorRecorder in - XCTAssertEqual(errorRecorder.errors.count, 0) + errorRecorder.errors.withLockedValue { errors in + XCTAssertEqual(errors.count, 0) + } }.wait() // On this child channel, write and flush an invalid headers frame. @@ -2023,13 +2140,17 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { // It should come through to the channel. try childChannel.pipeline.handler(type: ErrorRecorder.self).map { errorRecorder in - XCTAssertEqual( - errorRecorder.errors.first.flatMap { $0 as? NIOHTTP2Errors.ForbiddenHeaderField }, - NIOHTTP2Errors.forbiddenHeaderField(name: "transfer-encoding", value: "chunked") - ) + errorRecorder.errors.withLockedValue { errors in + XCTAssertEqual( + errors.first.flatMap { $0 as? NIOHTTP2Errors.ForbiddenHeaderField }, + NIOHTTP2Errors.forbiddenHeaderField(name: "transfer-encoding", value: "chunked") + ) + } }.wait() try secondChildChannel.pipeline.handler(type: ErrorRecorder.self).map { errorRecorder in - XCTAssertEqual(errorRecorder.errors.count, 0) + errorRecorder.errors.withLockedValue { errors in + XCTAssertEqual(errors.count, 0) + } }.wait() // Simulate closing the child channel in response to the error. @@ -2079,12 +2200,13 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { XCTAssertEqual(frames.count, 1) frames.first?.assertHeadersFrameMatches(this: HTTP2Frame(streamID: streamID, payload: .headers(payload))) + let channel: EmbeddedChannel = self.channel! try childChannel.pipeline.handler(type: ReadAndFrameConsumer.self).flatMapThrowing { consumer in XCTAssertEqual(consumer.readCount, 1) // 1. pass header onwards let responseHeaderPayload = HTTP2Frame.FramePayload.headers(.init(headers: [":status": "200"])) - XCTAssertNoThrow(try self.channel.writeInbound(HTTP2Frame(streamID: streamID, payload: responseHeaderPayload))) + XCTAssertNoThrow(try channel.writeInbound(HTTP2Frame(streamID: streamID, payload: responseHeaderPayload))) XCTAssertEqual(consumer.receivedFrames.count, 1) XCTAssertEqual(consumer.readCompleteCount, 1) @@ -2134,10 +2256,12 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { final class ErrorRecorder: ChannelInboundHandler { typealias InboundIn = Any - var errors: [Error] = [] + let errors = NIOLockedValueBox<[Error]>([]) func errorCaught(context: ChannelHandlerContext, error: Error) { - self.errors.append(error) + self.errors.withLockedValue { errors in + errors.append(error) + } context.fireErrorCaught(error) } } diff --git a/Tests/NIOHTTP2Tests/HTTP2InlineStreamMultiplexerTests.swift b/Tests/NIOHTTP2Tests/HTTP2InlineStreamMultiplexerTests.swift index f10a023..572a448 100644 --- a/Tests/NIOHTTP2Tests/HTTP2InlineStreamMultiplexerTests.swift +++ b/Tests/NIOHTTP2Tests/HTTP2InlineStreamMultiplexerTests.swift @@ -366,8 +366,8 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { 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 } + let closed = ManagedAtomic(false) + childChannel.close().whenComplete { _ in closed.store(true, ordering: .sequentiallyConsistent) } XCTAssertEqual(frameReceiver.flushedWrites.count, 1) var frameDecoder = HTTP2FrameDecoder(allocator: channel.allocator, expectClientMagic: false) if case .byteBuffer(let flushedWriteBuffer) = frameReceiver.flushedWrites[0] { @@ -375,7 +375,7 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { } let (flushedFrame, _) = try frameDecoder.nextFrame()! flushedFrame.assertRstStreamFrame(streamID: streamID, errorCode: .cancel) - XCTAssertTrue(closed) + XCTAssertTrue(closed.load(ordering: .sequentiallyConsistent)) } func testMultipleClosePromisesAreSatisfied() throws { @@ -404,26 +404,26 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { 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 + let firstClosed = ManagedAtomic(false) + let secondClosed = ManagedAtomic(false) + let thirdClosed = ManagedAtomic(false) childChannel.close().whenComplete { _ in - XCTAssertFalse(firstClosed) - XCTAssertFalse(secondClosed) - XCTAssertFalse(thirdClosed) - firstClosed = true + XCTAssertFalse(firstClosed.load(ordering: .sequentiallyConsistent)) + XCTAssertFalse(secondClosed.load(ordering: .sequentiallyConsistent)) + XCTAssertFalse(thirdClosed.load(ordering: .sequentiallyConsistent)) + firstClosed.store(true, ordering: .sequentiallyConsistent) } childChannel.close().whenComplete { _ in - XCTAssertTrue(firstClosed) - XCTAssertFalse(secondClosed) - XCTAssertFalse(thirdClosed) - secondClosed = true + XCTAssertTrue(firstClosed.load(ordering: .sequentiallyConsistent)) + XCTAssertFalse(secondClosed.load(ordering: .sequentiallyConsistent)) + XCTAssertFalse(thirdClosed.load(ordering: .sequentiallyConsistent)) + secondClosed.store(true, ordering: .sequentiallyConsistent) } childChannel.close().whenComplete { _ in - XCTAssertTrue(firstClosed) - XCTAssertTrue(secondClosed) - XCTAssertFalse(thirdClosed) - thirdClosed = true + XCTAssertTrue(firstClosed.load(ordering: .sequentiallyConsistent)) + XCTAssertTrue(secondClosed.load(ordering: .sequentiallyConsistent)) + XCTAssertFalse(thirdClosed.load(ordering: .sequentiallyConsistent)) + thirdClosed.store(true, ordering: .sequentiallyConsistent) } XCTAssertEqual(frameReceiver.flushedWrites.count, 1) var frameDecoder = HTTP2FrameDecoder(allocator: channel.allocator, expectClientMagic: false) @@ -432,7 +432,7 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { } let (flushedFrame, _) = try frameDecoder.nextFrame()! flushedFrame.assertRstStreamFrame(streamID: streamID, errorCode: .cancel) - XCTAssertTrue(thirdClosed) + XCTAssertTrue(thirdClosed.load(ordering: .sequentiallyConsistent)) XCTAssertNoThrow(try self.channel.finish()) } @@ -463,8 +463,12 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { 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 } + let closeError = NIOLockedValueBox(nil) + childChannel.close().whenFailure { error in + closeError.withLockedValue { closeError in + closeError = error + } + } XCTAssertEqual(frameReceiver.flushedWrites.count, 1) var frameDecoder = HTTP2FrameDecoder(allocator: channel.allocator, expectClientMagic: false) if case .byteBuffer(let flushedWriteBuffer) = frameReceiver.flushedWrites[0] { @@ -472,7 +476,9 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { } let (flushedFrame, _) = try frameDecoder.nextFrame()! flushedFrame.assertRstStreamFrame(streamID: streamID, errorCode: .cancel) - XCTAssertEqual(closeError as? NIOHTTP2Errors.StreamClosed, NIOHTTP2Errors.streamClosed(streamID: streamID, errorCode: .cancel)) + closeError.withLockedValue { closeError in + XCTAssertEqual(closeError as? NIOHTTP2Errors.StreamClosed, NIOHTTP2Errors.streamClosed(streamID: streamID, errorCode: .cancel)) + } XCTAssertNoThrow(try self.channel.finish()) } @@ -560,10 +566,10 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { // 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 } + let channelClosed = ManagedAtomic(false) + childChannel.closeFuture.whenComplete { _ in channelClosed.store(true, ordering: .sequentiallyConsistent) } XCTAssertEqual(writeRecorder.flushedWrites.count, 0) - XCTAssertFalse(channelClosed) + XCTAssertFalse(channelClosed.load(ordering: .sequentiallyConsistent)) setupCompletePromise.fail(MyError()) self.channel.assertNoFramesReceived() @@ -584,27 +590,21 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { XCTAssertEqual(frameRecorder.receivedFrames.count, 0) XCTAssertFalse(childChannel.isActive) XCTAssertEqual(writeRecorder.flushedWrites.count, 1) - XCTAssertFalse(channelClosed) + XCTAssertFalse(channelClosed.load(ordering: .sequentiallyConsistent)) (childChannel.eventLoop as! EmbeddedEventLoop).run() - XCTAssertTrue(channelClosed) + XCTAssertTrue(channelClosed.load(ordering: .sequentiallyConsistent)) XCTAssertNoThrow(try self.channel.finish()) } - func testFlushingOneChannelDoesntFlushThemAll() throws { + func testFlushingOneChannelDoesntFlushThemAll() async throws { let writeTracker = IODataWriteRecorder() - let channels = NIOLockedValueBox<[Channel]>([]) - let http2Handler = NIOHTTP2Handler( - mode: .server, - eventLoop: self.channel.eventLoop, - inboundStreamInitializer: { channel in - channels.withLockedValue { channels in - channels.append(channel) - } - return channel.eventLoop.makeSucceededVoidFuture() - } - ) + let (channelsStream, channelsContinuation) = AsyncStream.makeStream(of: Channel.self) + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in + channelsContinuation.yield(channel) + return channel.eventLoop.makeSucceededFuture(()) + }) XCTAssertNoThrow(try self.channel.pipeline.addHandler(writeTracker).wait()) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) XCTAssertNoThrow(try connectionSetup()) @@ -617,42 +617,35 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { 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) - } + + var streamChannelIterator = channelsStream.makeAsyncIterator() + let firstStreamChannel = await streamChannelIterator.next()! + let secondStreamChannel = await streamChannelIterator.next()! // 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() { + for channel in [firstStreamChannel, secondStreamChannel] { let frame = HTTP2Frame.FramePayload.headers(.init(headers: .basicResponseHeaders)) - channels.withLockedValue { channels in - channels[idx].write(frame, promise: nil) - } + channel.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() - } + firstStreamChannel.flush() XCTAssertEqual(writeTracker.flushedWrites.count, 1) // Now the other. - channels.withLockedValue { channels in - channels[1].flush() - } + secondStreamChannel.flush() XCTAssertEqual(writeTracker.flushedWrites.count, 2) XCTAssertNoThrow(try self.channel.finish()) } func testUnflushedWritesFailOnError() throws { - let childChannel = NIOLockedValueBox(nil) + let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in - childChannel.withLockedValue { childChannel in - childChannel = channel - } + childChannelPromise.succeed(channel) return channel.eventLoop.makeSucceededVoidFuture() }) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) @@ -663,32 +656,35 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders, endStream: true))) XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) XCTAssertNotNil(channel) + let childChannel = try childChannelPromise.futureResult.wait() // We will now write a headers frame to the channel, but don't flush it. - var writeError: Error? = nil + let writeError = NIOLockedValueBox(nil) let responseFrame = HTTP2Frame.FramePayload.headers(.init(headers: .basicResponseHeaders)) - childChannel.withLockedValue { childChannel in - childChannel!.write(responseFrame).whenFailure { - writeError = $0 + childChannel.write(responseFrame).whenFailure { error in + writeError.withLockedValue { writeError in + writeError = error } } - XCTAssertNil(writeError) + writeError.withLockedValue { writeError in + 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) + writeError.withLockedValue { writeError in + XCTAssertNotNil(writeError) + } XCTAssertNoThrow(try self.channel.finish()) } func testWritesFailOnClosedStreamChannels() throws { - let childChannel = NIOLockedValueBox(nil) + let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in - childChannel.withLockedValue { childChannel in - childChannel = channel - } + childChannelPromise.succeed(channel) return channel.pipeline.addHandler(TestHookHandler { context, payload in guard case .headers(let requestHeaders) = payload else { preconditionFailure("Expected request headers.") @@ -708,26 +704,28 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) XCTAssertNotNil(channel) + let childChannel = try childChannelPromise.futureResult.wait() + // We will now write a headers frame to the channel. This should fail immediately. - var writeError: Error? = nil + let writeError = NIOLockedValueBox(nil) let responseFrame = HTTP2Frame.FramePayload.headers(.init(headers: .basicRequestHeaders)) - childChannel.withLockedValue { childChannel in - childChannel!.write(responseFrame).whenFailure { - writeError = $0 + childChannel.write(responseFrame).whenFailure { error in + writeError.withLockedValue { writeError in + writeError = error } } - XCTAssertEqual(writeError as? ChannelError, ChannelError.ioOnClosedChannel) + writeError.withLockedValue { writeError in + XCTAssertEqual(writeError as? ChannelError, ChannelError.ioOnClosedChannel) + } XCTAssertNoThrow(try self.channel.finish()) } func testReadPullsInAllFrames() throws { - let childChannel = NIOLockedValueBox(nil) + let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) let frameRecorder = InboundFramePayloadRecorder() - let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { channel -> EventLoopFuture in - childChannel.withLockedValue { childChannel in - childChannel = channel - } + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel -> EventLoopFuture in + childChannelPromise.succeed(channel) // We're going to disable autoRead on this channel. return channel.getOption(ChannelOptions.autoRead).map { @@ -741,7 +739,7 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { }.flatMap { channel.pipeline.addHandler(frameRecorder) } - } + }) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) XCTAssertNoThrow(try connectionSetup()) @@ -749,7 +747,9 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { let streamID = HTTP2StreamID(1) let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders))) XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) - XCTAssertNotNil(childChannel) + + + let childChannel = try childChannelPromise.futureResult.wait() // Now we're going to deliver 5 data frames for this stream. let payloadBuffer = ByteBuffer(string: "Hello, world!") @@ -762,9 +762,7 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { XCTAssertEqual(frameRecorder.receivedFrames.count, 0) // We'll call read() on the child channel. - childChannel.withLockedValue { childChannel in - childChannel!.read() - } + childChannel.read() // All frames should now have been delivered. XCTAssertEqual(frameRecorder.receivedFrames.count, 6) @@ -833,12 +831,10 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { } func testReadWillCauseAutomaticFrameDelivery() throws { - let childChannel = NIOLockedValueBox(nil) + let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) let frameRecorder = InboundFramePayloadRecorder() let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { channel -> EventLoopFuture in - childChannel.withLockedValue { childChannel in - childChannel = channel - } + childChannelPromise.succeed(channel) // We're going to disable autoRead on this channel. return channel.setOption(ChannelOptions.autoRead, value: false).flatMap { @@ -852,21 +848,19 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { let streamID = HTTP2StreamID(1) let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders))) XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) - XCTAssertNotNil(childChannel) + + + let childChannel = try childChannelPromise.futureResult.wait() // 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() - } + childChannel.read() XCTAssertEqual(frameRecorder.receivedFrames.count, 1) // Call read again, nothing happens. - childChannel.withLockedValue { childChannel in - childChannel!.read() - } + childChannel.read() XCTAssertEqual(frameRecorder.receivedFrames.count, 1) // Now deliver a data frame. @@ -884,13 +878,11 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { } func testReadWithNoPendingDataCausesReadOnParentChannel() throws { - let childChannel = NIOLockedValueBox(nil) + let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) let readCounter = ReadCounter() let frameRecorder = InboundFramePayloadRecorder() let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { channel -> EventLoopFuture in - childChannel.withLockedValue { childChannel in - childChannel = channel - } + childChannelPromise.succeed(channel) // We're going to disable autoRead on this channel. return channel.setOption(ChannelOptions.autoRead, value: false).flatMap { @@ -905,27 +897,31 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { let streamID = HTTP2StreamID(1) let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders))) XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) - XCTAssertNotNil(childChannel) + + + let childChannel = try childChannelPromise.futureResult.wait() // This stream should have seen no frames. XCTAssertEqual(frameRecorder.receivedFrames.count, 0) // There should be no calls to read. - XCTAssertEqual(readCounter.readCount, 0) + readCounter.readCount.withLockedValue { readCount in + XCTAssertEqual(readCount, 0) + } // Call read, the header frame will come through. No calls to read on the parent stream. - childChannel.withLockedValue { childChannel in - childChannel!.read() - } + childChannel.read() XCTAssertEqual(frameRecorder.receivedFrames.count, 1) - XCTAssertEqual(readCounter.readCount, 0) + readCounter.readCount.withLockedValue { readCount in + XCTAssertEqual(readCount, 0) + } // Call read again, read is called on the parent stream. No frames delivered. - childChannel.withLockedValue { childChannel in - childChannel!.read() - } + childChannel.read() XCTAssertEqual(frameRecorder.receivedFrames.count, 1) - XCTAssertEqual(readCounter.readCount, 1) + readCounter.readCount.withLockedValue { readCount in + XCTAssertEqual(readCount, 1) + } // Now deliver a data frame. let dataFrame = try HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(ByteBuffer(string: "Hello, world!"))))).encode() @@ -933,36 +929,40 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { // This frame should have been immediately delivered. No extra call to read. XCTAssertEqual(frameRecorder.receivedFrames.count, 2) - XCTAssertEqual(readCounter.readCount, 1) + readCounter.readCount.withLockedValue { readCount in + XCTAssertEqual(readCount, 1) + } // Another call to read issues a read to the parent stream. - childChannel.withLockedValue { childChannel in - childChannel!.read() - } + childChannel.read() XCTAssertEqual(frameRecorder.receivedFrames.count, 2) - XCTAssertEqual(readCounter.readCount, 2) + readCounter.readCount.withLockedValue { readCount in + XCTAssertEqual(readCount, 2) + } // Another call to read, this time does not issue a read to the parent stream. - childChannel.withLockedValue { childChannel in - childChannel!.read() - } + childChannel.read() XCTAssertEqual(frameRecorder.receivedFrames.count, 2) - XCTAssertEqual(readCounter.readCount, 2) + readCounter.readCount.withLockedValue { readCount in + XCTAssertEqual(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) + readCounter.readCount.withLockedValue { readCount in + XCTAssertEqual(readCount, 2) + } XCTAssertNoThrow(try self.channel.finish()) } func testHandlersAreRemovedOnClosure() throws { - var handlerRemoved = false + let handlerRemoved = ManagedAtomic(false) let handlerRemovedPromise: EventLoopPromise = self.channel.eventLoop.makePromise() - handlerRemovedPromise.futureResult.whenComplete { _ in handlerRemoved = true } + handlerRemovedPromise.futureResult.whenComplete { _ in handlerRemoved.store(true, ordering: .sequentiallyConsistent) } let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in return channel.pipeline.addHandlers([ @@ -986,19 +986,19 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) // No handlerRemoved so far. - XCTAssertFalse(handlerRemoved) + XCTAssertFalse(handlerRemoved.load(ordering: .sequentiallyConsistent)) // The handlers will only be removed after we spin the loop. (self.channel.eventLoop as! EmbeddedEventLoop).run() - XCTAssertTrue(handlerRemoved) + XCTAssertTrue(handlerRemoved.load(ordering: .sequentiallyConsistent)) XCTAssertNoThrow(try self.channel.finish()) } func testHandlersAreRemovedOnClosureWithError() throws { - var handlerRemoved = false + let handlerRemoved = ManagedAtomic(false) let handlerRemovedPromise: EventLoopPromise = self.channel.eventLoop.makePromise() - handlerRemovedPromise.futureResult.whenComplete { _ in handlerRemoved = true } + handlerRemovedPromise.futureResult.whenComplete { _ in handlerRemoved.store(true, ordering: .sequentiallyConsistent) } let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { channel in return channel.pipeline.addHandlers([ @@ -1022,11 +1022,11 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) // No handlerRemoved so far. - XCTAssertFalse(handlerRemoved) + XCTAssertFalse(handlerRemoved.load(ordering: .sequentiallyConsistent)) // The handlers will only be removed after we spin the loop. (self.channel.eventLoop as! EmbeddedEventLoop).run() - XCTAssertTrue(handlerRemoved) + XCTAssertTrue(handlerRemoved.load(ordering: .sequentiallyConsistent)) XCTAssertNoThrow(try self.channel.finish()) } @@ -1034,16 +1034,12 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { 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, - inboundStreamInitializer: { _ in - XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) - } - ) + let configuredChannelCount = ManagedAtomic(0) + let streamIDs = NIOLockedValueBox(Array()) + let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in + XCTFail("Must not be called") + return 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 @@ -1055,11 +1051,13 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { return configurePromise.futureResult } channelPromise.futureResult.whenSuccess { channel in - configuredChannelCount += 1 + configuredChannelCount.wrappingIncrement(ordering: .sequentiallyConsistent) // 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) + streamIDs.withLockedValue { streamIDs in + streamIDs.append(streamID) + } } } } @@ -1069,13 +1067,17 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { self.channel.embeddedEventLoop.run() XCTAssertEqual(createdChannelCount.load(ordering: .sequentiallyConsistent), 3) - XCTAssertEqual(configuredChannelCount, 0) - XCTAssertEqual(streamIDs.count, 0) + XCTAssertEqual(configuredChannelCount.load(ordering: .sequentiallyConsistent), 0) + streamIDs.withLockedValue { streamIDs in + XCTAssertEqual(streamIDs.count, 0) + } configurePromise.succeed(()) XCTAssertEqual(createdChannelCount.load(ordering: .sequentiallyConsistent), 3) - XCTAssertEqual(configuredChannelCount, 3) - XCTAssertEqual(streamIDs, [1, 3, 5].map { HTTP2StreamID($0) }) + XCTAssertEqual(configuredChannelCount.load(ordering: .sequentiallyConsistent), 3) + streamIDs.withLockedValue { streamIDs in + XCTAssertEqual(streamIDs, [1, 3, 5].map { HTTP2StreamID($0) }) + } XCTAssertNoThrow(try self.channel.finish()) } @@ -1083,18 +1085,14 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { func testWritesOnCreatedChannelAreDelayed() throws { let configurePromise: EventLoopPromise = self.channel.eventLoop.makePromise() let writeRecorder = IODataWriteRecorder() - let childChannel = NIOLockedValueBox(nil) + let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) - let http2Handler = NIOHTTP2Handler( - mode: .client, eventLoop: - self.channel.eventLoop, - inboundStreamInitializer: { _ in - XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) - } - ) + let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in + XCTFail("Must not be called") + return 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() @@ -1102,17 +1100,16 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { let multiplexer = try http2Handler.multiplexer.wait() multiplexer.createStreamChannel(promise: nil) { channel in - childChannel.withLockedValue { childChannel in - childChannel = channel - } + childChannelPromise.succeed(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) - } + + let childChannel = try childChannelPromise.futureResult.wait() + + childChannel.writeAndFlush(HTTP2Frame.FramePayload.headers(.init(headers: .basicRequestHeaders)), promise: nil) + XCTAssertEqual(writeRecorder.flushedWrites.count, 0) configurePromise.succeed(()) @@ -1124,35 +1121,37 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { func testWritesAreCancelledOnFailingInitializer() throws { let configurePromise: EventLoopPromise = self.channel.eventLoop.makePromise() - let childChannel = NIOLockedValueBox(nil) + let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) - let http2Handler = NIOHTTP2Handler( - mode: .server, - eventLoop: self.channel.eventLoop, - inboundStreamInitializer: { _ in - XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) - } - ) + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in + XCTFail("Must not be called") + return 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 - } + childChannelPromise.succeed(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 } + let childChannel = try childChannelPromise.futureResult.wait() + + let writeError = NIOLockedValueBox(nil) + childChannel.writeAndFlush(HTTP2Frame.FramePayload.headers(.init(headers: .basicRequestHeaders))).whenFailure { error in + writeError.withLockedValue { writeError in + writeError = error + } + } + writeError.withLockedValue { writeError in + XCTAssertNil(writeError) } - XCTAssertNil(writeError) configurePromise.fail(MyError()) - XCTAssertNotNil(writeError) - XCTAssertTrue(writeError is MyError) + writeError.withLockedValue { writeError in + XCTAssertNotNil(writeError) + XCTAssertTrue(writeError is MyError) + } XCTAssertNoThrow(try self.channel.finish()) } @@ -1161,14 +1160,10 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { let configurePromise: EventLoopPromise = self.channel.eventLoop.makePromise() let writeRecorder = FrameWriteRecorder() - let http2Handler = NIOHTTP2Handler( - mode: .server, - eventLoop: self.channel.eventLoop, - inboundStreamInitializer: { _ in - XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) - } - ) + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in + XCTFail("Must not be called") + return 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() @@ -1184,69 +1179,61 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { } func testCreatedChildChannelDoesNotActivateEarly() throws { - var activated = false + let activated = ManagedAtomic(false) let activePromise: EventLoopPromise = self.channel.eventLoop.makePromise() - let activeRecorder = ActiveHandler(activatedPromise: activePromise) activePromise.futureResult.map { - activated = true + activated.store(true, ordering: .sequentiallyConsistent) }.whenFailure { (_: Error) in XCTFail("Activation promise must not fail") } - let http2Handler = NIOHTTP2Handler( - mode: .server, - eventLoop: self.channel.eventLoop, - inboundStreamInitializer: { _ in - XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) - } - ) + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in + XCTFail("Must not be called") + return channel.eventLoop.makeFailedFuture(MyError()) + }) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) let multiplexer = try http2Handler.multiplexer.wait() multiplexer.createStreamChannel(promise: nil) { channel in + let activeRecorder = ActiveHandler(activatedPromise: activePromise) return channel.pipeline.addHandler(activeRecorder) } (self.channel.eventLoop as! EmbeddedEventLoop).run() - XCTAssertFalse(activated) + XCTAssertFalse(activated.load(ordering: .sequentiallyConsistent)) XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) - XCTAssertTrue(activated) + XCTAssertTrue(activated.load(ordering: .sequentiallyConsistent)) XCTAssertNoThrow(try self.channel.finish()) } func testCreatedChildChannelActivatesIfParentIsActive() throws { - var activated = false + let activated = ManagedAtomic(false) let activePromise: EventLoopPromise = self.channel.eventLoop.makePromise() - let activeRecorder = ActiveHandler(activatedPromise: activePromise) activePromise.futureResult.map { - activated = true + activated.store(true, ordering: .sequentiallyConsistent) }.whenFailure { (_: Error) in XCTFail("Activation promise must not fail") } - let http2Handler = NIOHTTP2Handler( - mode: .server, - eventLoop: self.channel.eventLoop, - inboundStreamInitializer: { _ in - XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) - } - ) + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in + XCTFail("Must not be called") + return 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) + XCTAssertFalse(activated.load(ordering: .sequentiallyConsistent)) let multiplexer = try http2Handler.multiplexer.wait() multiplexer.createStreamChannel(promise: nil) { channel in + let activeRecorder = ActiveHandler(activatedPromise: activePromise) return channel.pipeline.addHandler(activeRecorder) } (self.channel.eventLoop as! EmbeddedEventLoop).run() - XCTAssertTrue(activated) + XCTAssertTrue(activated.load(ordering: .sequentiallyConsistent)) XCTAssertNoThrow(try self.channel.finish()) } @@ -1254,17 +1241,17 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { func testInitiatedChildChannelActivates() throws { XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) - var activated = false + let activated = ManagedAtomic(false) let activePromise: EventLoopPromise = self.channel.eventLoop.makePromise() - let activeRecorder = ActiveHandler(activatedPromise: activePromise) activePromise.futureResult.map { - activated = true + activated.store(true, ordering: .sequentiallyConsistent) }.whenFailure { (_: Error) in XCTFail("Activation promise must not fail") } let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in + let activeRecorder = ActiveHandler(activatedPromise: activePromise) return channel.pipeline.addHandler(activeRecorder) }) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) @@ -1272,11 +1259,11 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { self.channel.pipeline.fireChannelActive() // Open a new stream. - XCTAssertFalse(activated) + XCTAssertFalse(activated.load(ordering: .sequentiallyConsistent)) let streamID = HTTP2StreamID(1) let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders))) XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) - XCTAssertTrue(activated) + XCTAssertTrue(activated.load(ordering: .sequentiallyConsistent)) XCTAssertNoThrow(try self.channel.finish()) } @@ -1295,15 +1282,15 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { func testMultiplexerForwardsActiveToParent() throws { self.channel.addNoOpInlineMultiplexer(mode: .client, eventLoop: self.channel.eventLoop) - var didActivate = false + let activated = ManagedAtomic(false) let activePromise = self.channel.eventLoop.makePromise(of: Void.self) activePromise.futureResult.whenSuccess { - didActivate = true + activated.store(true, ordering: .sequentiallyConsistent) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(ActiveHandler(activatedPromise: activePromise)).wait()) XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/nothing")).wait()) - XCTAssertTrue(didActivate) + XCTAssertTrue(activated.load(ordering: .sequentiallyConsistent)) XCTAssertNoThrow(try self.channel.finish()) } @@ -1311,14 +1298,10 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { func testCreatedChildChannelCanBeClosedImmediately() throws { let closed = ManagedAtomic(false) - let http2Handler = NIOHTTP2Handler( - mode: .client, - eventLoop: self.channel.eventLoop, - inboundStreamInitializer: { channel in - XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) - } - ) + let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in + XCTFail("Must not be called") + return channel.eventLoop.makeFailedFuture(MyError()) + }) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) XCTAssertFalse(closed.load(ordering: .sequentiallyConsistent)) @@ -1333,16 +1316,12 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { } func testCreatedChildChannelCanBeClosedBeforeWritingHeaders() throws { - var closed = false + let closed = ManagedAtomic(false) - let http2Handler = NIOHTTP2Handler( - mode: .client, - eventLoop: self.channel.eventLoop, - inboundStreamInitializer: { channel in - XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) - } - ) + let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in + XCTFail("Must not be called") + return channel.eventLoop.makeFailedFuture(MyError()) + }) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) let channelPromise = self.channel.eventLoop.makePromise(of: Channel.self) @@ -1353,12 +1332,14 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { self.channel.embeddedEventLoop.run() let child = try assertNoThrowWithValue(channelPromise.futureResult.wait()) - child.closeFuture.whenComplete { _ in closed = true } + child.closeFuture.whenComplete { _ in + closed.store(true, ordering: .sequentiallyConsistent) + } - XCTAssertFalse(closed) + XCTAssertFalse(closed.load(ordering: .sequentiallyConsistent)) child.close(promise: nil) self.channel.embeddedEventLoop.run() - XCTAssertTrue(closed) + XCTAssertTrue(closed.load(ordering: .sequentiallyConsistent)) XCTAssertNoThrow(XCTAssertTrue(try self.channel.finish().isClean)) } @@ -1368,14 +1349,10 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { // 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, - inboundStreamInitializer: { channel in - XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) - } - ) + let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in + XCTFail("Must not be called") + return channel.eventLoop.makeFailedFuture(MyError()) + }) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) XCTAssertEqual(try self.channel.readAllBuffers().count, 2) // magic & settings @@ -1392,19 +1369,15 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { } func testCreatedChildChannelCanBeClosedBeforeWritingHeadersWhenBaseIsActive() throws { - var closed = false + 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, - inboundStreamInitializer: { channel in - XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) - } - ) + let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in + XCTFail("Must not be called") + return channel.eventLoop.makeFailedFuture(MyError()) + }) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) XCTAssertEqual(try self.channel.readAllBuffers().count, 2) // magic & settings @@ -1416,13 +1389,15 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { self.channel.embeddedEventLoop.run() let child = try assertNoThrowWithValue(channelPromise.futureResult.wait()) - child.closeFuture.whenComplete { _ in closed = true } + child.closeFuture.whenComplete { _ in + closed.store(true, ordering: .sequentiallyConsistent) + } - XCTAssertFalse(closed) + XCTAssertFalse(closed.load(ordering: .sequentiallyConsistent)) child.close(promise: nil) self.channel.embeddedEventLoop.run() - XCTAssertTrue(closed) + XCTAssertTrue(closed.load(ordering: .sequentiallyConsistent)) XCTAssertNoThrow(XCTAssertTrue(try self.channel.finish().isClean)) } @@ -1471,7 +1446,9 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try connectionSetup()) XCTAssertEqual(frameRecorder.receivedFrames.count, 0) - XCTAssertEqual(readCompleteCounter.readCompleteCount, 0) + readCompleteCounter.readCompleteCount.withLockedValue { readCompleteCount in + XCTAssertEqual(readCompleteCount, 0) + } // Wake up and activate the stream. let requestHeaders = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) @@ -1480,7 +1457,9 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { self.channel.embeddedEventLoop.run() XCTAssertEqual(frameRecorder.receivedFrames.count, 1) - XCTAssertEqual(readCompleteCounter.readCompleteCount, 1) + readCompleteCounter.readCompleteCount.withLockedValue { readCompleteCount in + XCTAssertEqual(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() @@ -1490,19 +1469,25 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { // We should have 1 read (the HEADERS), and one read complete. XCTAssertEqual(frameRecorder.receivedFrames.count, 1) - XCTAssertEqual(readCompleteCounter.readCompleteCount, 1) + readCompleteCounter.readCompleteCount.withLockedValue { readCompleteCount in + XCTAssertEqual(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) + readCompleteCounter.readCompleteCount.withLockedValue { readCompleteCount in + XCTAssertEqual(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) + readCompleteCounter.readCompleteCount.withLockedValue { readCompleteCount in + XCTAssertEqual(readCompleteCount, 2) + } } func testMultiplexerCorrectlyTellsAllStreamsAboutReadComplete() throws { @@ -1520,7 +1505,9 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try connectionSetup()) XCTAssertEqual(frameRecorder.receivedFrames.count, 0) - XCTAssertEqual(readCompleteCounter.readCompleteCount, 0) + readCompleteCounter.readCompleteCount.withLockedValue { readCompleteCount in + XCTAssertEqual(readCompleteCount, 0) + } // Wake up and activate the streams. let requestHeaders = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) @@ -1531,12 +1518,16 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { self.channel.embeddedEventLoop.run() XCTAssertEqual(frameRecorder.receivedFrames.count, 3) - XCTAssertEqual(readCompleteCounter.readCompleteCount, 3) + readCompleteCounter.readCompleteCount.withLockedValue { readCompleteCount in + XCTAssertEqual(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) + readCompleteCounter.readCompleteCount.withLockedValue { readCompleteCount in + XCTAssertEqual(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!"))))) @@ -1544,7 +1535,9 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { // 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) + readCompleteCounter.readCompleteCount.withLockedValue { readCompleteCount in + XCTAssertEqual(readCompleteCount, 3) + } // Fire read complete on the parent and it'll propagate to the child, but only to the one // that saw a frame. @@ -1552,27 +1545,26 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { // We should have 4 reads, and 4 read completes. XCTAssertEqual(frameRecorder.receivedFrames.count, 4) - XCTAssertEqual(readCompleteCounter.readCompleteCount, 4) + readCompleteCounter.readCompleteCount.withLockedValue { readCompleteCount in + XCTAssertEqual(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) + readCompleteCounter.readCompleteCount.withLockedValue { readCompleteCount in + XCTAssertEqual(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, - inboundStreamInitializer: { _ in - XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) - } - ) + let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: self.channel.eventLoop, streamConfiguration: streamConfiguration, inboundStreamInitializer: { channel in + XCTFail("Must not be called") + return channel.eventLoop.makeFailedFuture(MyError()) + }) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) // We need to activate the underlying channel here. @@ -1622,14 +1614,11 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { } func testMultiplexerModifiesStreamChannelWritabilityBasedOnParentChannelWritability() throws { - let http2Handler = NIOHTTP2Handler( - mode: .client, eventLoop: - self.channel.eventLoop, - inboundStreamInitializer: { _ in - XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) - } - ) + + let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in + XCTFail("Must not be called") + return channel.eventLoop.makeFailedFuture(MyError()) + }) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) // We need to activate the underlying channel here. @@ -1639,7 +1628,7 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { 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 + multiplexer.createStreamChannel(promise: promise) { childChannel in return childChannel.eventLoop.makeSucceededFuture(()) } } @@ -1672,15 +1661,10 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { var streamConfiguration = NIOHTTP2Handler.StreamConfiguration() streamConfiguration.outboundBufferSizeHighWatermark = 100 streamConfiguration.outboundBufferSizeLowWatermark = 50 - let http2Handler = NIOHTTP2Handler( - mode: .client, - eventLoop: self.channel.eventLoop, - streamConfiguration: streamConfiguration, - inboundStreamInitializer: { _ in - XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) - } - ) + let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: self.channel.eventLoop, streamConfiguration: streamConfiguration, inboundStreamInitializer: { channel in + XCTFail("Must not be called") + return channel.eventLoop.makeFailedFuture(MyError()) + }) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) // We need to activate the underlying channel here. @@ -1746,15 +1730,10 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { var streamConfiguration = NIOHTTP2Handler.StreamConfiguration() streamConfiguration.outboundBufferSizeHighWatermark = 100 streamConfiguration.outboundBufferSizeLowWatermark = 50 - let http2Handler = NIOHTTP2Handler( - mode: .client, - eventLoop: self.channel.eventLoop, - streamConfiguration: streamConfiguration, - inboundStreamInitializer: { _ in - XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) - } - ) + let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: self.channel.eventLoop, streamConfiguration: streamConfiguration, inboundStreamInitializer: { channel in + XCTFail("Must not be called") + return channel.eventLoop.makeFailedFuture(MyError()) + }) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) // We need to activate the underlying channel here. @@ -1772,12 +1751,10 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { } func testReadWhenUsingAutoreadOnChildChannel() throws { - let childChannel = NIOLockedValueBox(nil) + let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) let readCounter = ReadCounter() let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { channel -> EventLoopFuture in - childChannel.withLockedValue { childChannel in - childChannel = channel - } + childChannelPromise.succeed(channel) // We're going to _enable_ autoRead on this channel. return channel.setOption(ChannelOptions.autoRead, value: true).flatMap { @@ -1787,29 +1764,34 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { 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) - } + let _ = try childChannelPromise.futureResult.wait() // just ensure that the initializer ran // 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) + readCounter.readCount.withLockedValue { readCount in + XCTAssertEqual(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) + readCounter.readCount.withLockedValue { readCount in + XCTAssertEqual(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) + readCounter.readCount.withLockedValue { readCount in + XCTAssertEqual(readCount, 5) + } XCTAssertNoThrow(try self.channel.finish()) } @@ -1859,43 +1841,57 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { 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 firstChildChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) let multiplexer = try http2Handler.multiplexer.wait() multiplexer.createStreamChannel(promise: nil) { channel in - childChannel.withLockedValue { childChannel in - childChannel = channel - } - return channel.pipeline.addHandler(errorRecorder) + firstChildChannelPromise.succeed(channel) + return channel.pipeline.addHandler(ErrorRecorder()) } - let secondErrorRecorder = ErrorRecorder() + let secondChildChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) multiplexer.createStreamChannel(promise: nil) { channel in + secondChildChannelPromise.succeed(channel) // 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) + return channel.pipeline.addHandler(ErrorRecorder()) } 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) + let firstChildChannel = try firstChildChannelPromise.futureResult.wait() + let secondChildChannel = try secondChildChannelPromise.futureResult.wait() - childChannel.withLockedValue { childChannel in - childChannel!.writeAndFlush(HTTP2Frame.FramePayload.headers(.init(headers: badHeaders)), promise: nil) + // On this child channel, write and flush an invalid headers frame. + _ = firstChildChannel.pipeline.handler(type: ErrorRecorder.self).map { errorRecorder in + errorRecorder.errors.withLockedValue { errors in + XCTAssertEqual(errors.count, 0) + } } + _ = secondChildChannel.pipeline.handler(type: ErrorRecorder.self).map { errorRecorder in + errorRecorder.errors.withLockedValue { errors in + XCTAssertEqual(errors.count, 0) + } + } + + firstChildChannel.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) + _ = firstChildChannel.pipeline.handler(type: ErrorRecorder.self).map { errorRecorder in + errorRecorder.errors.withLockedValue { errors in + XCTAssertEqual( + errors.first.flatMap { $0 as? NIOHTTP2Errors.ForbiddenHeaderField }, + NIOHTTP2Errors.forbiddenHeaderField(name: "transfer-encoding", value: "chunked") + ) + } + } + + _ = secondChildChannel.pipeline.handler(type: ErrorRecorder.self).map { errorRecorder in + errorRecorder.errors.withLockedValue { errors in + XCTAssertEqual(errors.count, 0) + } + } // Simulate closing the child channel in response to the error. - childChannel.withLockedValue { childChannel in - childChannel!.close(promise: nil) - } + firstChildChannel.close(promise: nil) self.channel.embeddedEventLoop.run() // Only the HEADERS frames should have been written: we closed before the other channel became active, so @@ -1923,96 +1919,117 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { 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) + // Now create and save a child channel with an error recording handler in it.x + let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) let multiplexer = try http2Handler.multiplexer.wait() - multiplexer.createStreamChannel(promise: nil) { channel in - childChannel.withLockedValue { childChannel in - childChannel = channel - } + multiplexer.createStreamChannel(promise: childChannelPromise) { channel in + let consumer = ReadAndFrameConsumer() return channel.pipeline.addHandler(consumer) } self.channel.embeddedEventLoop.run() + let childChannel = try childChannelPromise.futureResult.wait() + 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()) - } + + 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) + try childChannel.pipeline.handler(type: ReadAndFrameConsumer.self).map { consumer in + XCTAssertEqual(consumer.readCount, 1) + }.wait() // 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) + try childChannel.pipeline.handler(type: ReadAndFrameConsumer.self).map { consumer in + XCTAssertEqual(consumer.receivedFrames.count, 1) + XCTAssertEqual(consumer.readCompleteCount, 1) + XCTAssertEqual(consumer.readCount, 2) - consumer.forwardRead = false + consumer.forwardRead = false + }.wait() // 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) + + try childChannel.pipeline.handler(type: ReadAndFrameConsumer.self).map { consumer in + XCTAssertEqual(consumer.receivedFrames.count, 2) + XCTAssertEqual(consumer.readCompleteCount, 2) + XCTAssertEqual(consumer.readCount, 3) + XCTAssertEqual(consumer.readPending, true) + }.wait() // 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) + + try childChannel.pipeline.handler(type: ReadAndFrameConsumer.self).map { consumer in + XCTAssertEqual(consumer.receivedFrames.count, 2) + XCTAssertEqual(consumer.readCompleteCount, 2) + XCTAssertEqual(consumer.readCount, 3) + XCTAssertEqual(consumer.readPending, true) + }.wait() // 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) + + try childChannel.pipeline.handler(type: ReadAndFrameConsumer.self).map { consumer in + XCTAssertEqual(consumer.receivedFrames.count, 4) + XCTAssertEqual(consumer.readCompleteCount, 3) + XCTAssertEqual(consumer.readCount, 3) + XCTAssertEqual(consumer.channelInactiveCount, 1) + XCTAssertEqual(consumer.readPending, true) + }.wait() } fileprivate struct CountingStreamDelegate: NIOHTTP2StreamDelegate { - private var store = Store() + private let store = NIOLockedValueBox(Store()) func streamCreated(_ id: NIOHTTP2.HTTP2StreamID, channel: NIOCore.Channel) { - self.store.created+=1 - self.store.open+=1 + self.store.withLockedValue { store in + store.created+=1 + store.open+=1 + } } func streamClosed(_ id: NIOHTTP2.HTTP2StreamID, channel: NIOCore.Channel) { - self.store.closed+=1 - self.store.open-=1 + self.store.withLockedValue { store in + store.closed+=1 + store.open-=1 + } } var created: Int { - self.store.created + self.store.withLockedValue { store in + store.created + } } var closed: Int { - self.store.closed + self.store.withLockedValue { store in + store.closed + } } var open: Int { - self.store.open + self.store.withLockedValue { store in + store.open + } } - class Store { + struct Store { var created: Int = 0 var closed: Int = 0 var open: Int = 0 @@ -2071,17 +2088,12 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { let streamDelegate = CountingStreamDelegate() 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, - streamDelegate: streamDelegate, - inboundStreamInitializer: { _ in - XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) - } - ) + let configuredChannelCount = ManagedAtomic(0) + let streamIDs = NIOLockedValueBox(Array()) + let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: self.channel.eventLoop, streamDelegate: streamDelegate, inboundStreamInitializer: { channel in + XCTFail("Must not be called") + return channel.eventLoop.makeFailedFuture(MyError()) + }) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) try connectionSetup(mode: .client) @@ -2093,11 +2105,13 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { return configurePromise.futureResult } channelPromise.futureResult.whenSuccess { channel in - configuredChannelCount += 1 + configuredChannelCount.wrappingIncrement(ordering: .sequentiallyConsistent) // Write some headers: the flush will trigger a stream ID to be assigned to the channel. channel.writeAndFlush(HTTP2Frame.FramePayload.headers(.init(headers: .basicRequestHeaders, endStream: true))).whenSuccess { channel.getOption(HTTP2StreamChannelOptions.streamID).whenSuccess { streamID in - streamIDs.append(streamID) + streamIDs.withLockedValue { streamIDs in + streamIDs.append(streamID) + } } } } @@ -2107,24 +2121,30 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { self.channel.embeddedEventLoop.run() XCTAssertEqual(createdChannelCount.load(ordering: .sequentiallyConsistent), 3) - XCTAssertEqual(configuredChannelCount, 0) - XCTAssertEqual(streamIDs.count, 0) + XCTAssertEqual(configuredChannelCount.load(ordering: .sequentiallyConsistent), 0) + streamIDs.withLockedValue { streamIDs in + XCTAssertEqual(streamIDs.count, 0) + } XCTAssertEqual(streamDelegate.created, 0) XCTAssertEqual(streamDelegate.closed, 0) XCTAssertEqual(streamDelegate.open, 0) configurePromise.succeed(()) XCTAssertEqual(createdChannelCount.load(ordering: .sequentiallyConsistent), 3) - XCTAssertEqual(configuredChannelCount, 3) - XCTAssertEqual(streamIDs, [1, 3, 5].map { HTTP2StreamID($0) }) + XCTAssertEqual(configuredChannelCount.load(ordering: .sequentiallyConsistent), 3) + streamIDs.withLockedValue { streamIDs in + XCTAssertEqual(streamIDs, [1, 3, 5].map { HTTP2StreamID($0) }) + } XCTAssertEqual(streamDelegate.created, 3) XCTAssertEqual(streamDelegate.closed,0) XCTAssertEqual(streamDelegate.open, 3) // write a response to allow the streams to fully closes - for id in streamIDs { - let headers = HTTP2Frame(streamID: id, payload: .headers(.init(headers: .basicResponseHeaders, endStream: true))) - XCTAssertNoThrow(try self.channel.writeInbound(headers.encode())) + try streamIDs.withLockedValue { streamIDs in + for id in streamIDs { + let headers = HTTP2Frame(streamID: id, payload: .headers(.init(headers: .basicResponseHeaders, endStream: true))) + XCTAssertNoThrow(try self.channel.writeInbound(headers.encode())) + } } (self.channel.eventLoop as! EmbeddedEventLoop).run() diff --git a/Tests/NIOHTTP2Tests/HTTP2StreamMultiplexerTests.swift b/Tests/NIOHTTP2Tests/HTTP2StreamMultiplexerTests.swift index c95cdef..33bef11 100644 --- a/Tests/NIOHTTP2Tests/HTTP2StreamMultiplexerTests.swift +++ b/Tests/NIOHTTP2Tests/HTTP2StreamMultiplexerTests.swift @@ -13,6 +13,7 @@ //===----------------------------------------------------------------------===// import XCTest +import Atomics import NIOConcurrencyHelpers import NIOCore import NIOEmbedded @@ -119,14 +120,16 @@ typealias InboundFrameRecorder = InboundRecorder typealias InboundFramePayloadRecorder = InboundRecorder /// A handler that tracks the number of times read() was called on the channel. -final class ReadCounter: ChannelOutboundHandler { +final class ReadCounter: ChannelOutboundHandler, Sendable { typealias OutboundIn = Any typealias OutboundOut = Any - var readCount = 0 + let readCount = NIOLockedValueBox(0) func read(context: ChannelHandlerContext) { - readCount += 1 + self.readCount.withLockedValue { readCount in + readCount += 1 + } context.read() } } @@ -146,14 +149,16 @@ final class FlushCounter: ChannelOutboundHandler { } -final class ReadCompleteCounter: ChannelInboundHandler { +final class ReadCompleteCounter: ChannelInboundHandler, Sendable { typealias InboundIn = Any typealias InboundOut = Any - var readCompleteCount = 0 + let readCompleteCount = NIOLockedValueBox(0) func channelReadComplete(context: ChannelHandlerContext) { - self.readCompleteCount += 1 + self.readCompleteCount.withLockedValue { readCompleteCount in + readCompleteCount += 1 + } context.fireChannelReadComplete() } } @@ -266,9 +271,9 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testHeadersFramesCreateNewChannels() throws { - var channelCount = 0 + let channelCount = ManagedAtomic(0) let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (channel, _) in - channelCount += 1 + channelCount.wrappingIncrement(ordering: .sequentiallyConsistent) return channel.close() } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -279,17 +284,15 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.writeInbound(frame)) } - XCTAssertEqual(channelCount, 50) + XCTAssertEqual(channelCount.load(ordering: .sequentiallyConsistent), 50) XCTAssertNoThrow(try self.channel.finish()) } @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testChannelsCloseThemselvesWhenToldTo() throws { - var completedChannelCount = 0 - var closeFutures: [EventLoopFuture] = [] + let completedChannelCount = ManagedAtomic(0) let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (channel, _) in - closeFutures.append(channel.closeFuture) - channel.closeFuture.whenSuccess { completedChannelCount += 1 } + channel.closeFuture.whenSuccess { completedChannelCount.wrappingIncrement(ordering: .sequentiallyConsistent) } return channel.eventLoop.makeSucceededFuture(()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -300,7 +303,7 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders(), endStream: true))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) } - XCTAssertEqual(completedChannelCount, 0) + XCTAssertEqual(completedChannelCount.load(ordering: .sequentiallyConsistent), 0) // Now we send them all a clean exit. for streamID in streamIDs { @@ -310,13 +313,13 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { (self.channel.eventLoop as! EmbeddedEventLoop).run() // At this stage all the promises should be completed. - XCTAssertEqual(completedChannelCount, 50) + XCTAssertEqual(completedChannelCount.load(ordering: .sequentiallyConsistent), 50) XCTAssertNoThrow(try self.channel.finish()) } @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testChannelsCloseAfterResetStreamFrameFirstThenEvent() throws { - var closeError: Error? = nil + let closeError = NIOLockedValueBox(nil) XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) @@ -326,8 +329,14 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { let rstStreamFrame = HTTP2Frame(streamID: streamID, payload: .rstStream(.cancel)) let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (channel, _) in - XCTAssertNil(closeError) - channel.closeFuture.whenFailure { closeError = $0 } + closeError.withLockedValue { closeError in + XCTAssertNil(closeError) + } + channel.closeFuture.whenFailure { error in + closeError.withLockedValue { closeError in + closeError = error + } + } return channel.pipeline.addHandler(FrameExpecter(expectedFrames: [frame, rstStreamFrame])) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -335,7 +344,9 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { // Let's open the stream up. XCTAssertNoThrow(try self.channel.writeInbound(frame)) self.activateStream(streamID) - XCTAssertNil(closeError) + closeError.withLockedValue { closeError in + XCTAssertNil(closeError) + } // Now we can send a RST_STREAM frame. XCTAssertNoThrow(try self.channel.writeInbound(rstStreamFrame)) @@ -346,14 +357,16 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { (self.channel.eventLoop as! EmbeddedEventLoop).run() // At this stage the stream should be closed with the appropriate error code. - XCTAssertEqual(closeError as? NIOHTTP2Errors.StreamClosed, - NIOHTTP2Errors.StreamClosed(streamID: streamID, errorCode: .cancel)) + closeError.withLockedValue { closeError in + XCTAssertEqual(closeError as? NIOHTTP2Errors.StreamClosed, + NIOHTTP2Errors.StreamClosed(streamID: streamID, errorCode: .cancel)) + } XCTAssertNoThrow(try self.channel.finish()) } @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testChannelsCloseAfterGoawayFrameFirstThenEvent() throws { - var closeError: Error? = nil + let closeError = NIOLockedValueBox(nil) XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) @@ -363,8 +376,14 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { let goAwayFrame = HTTP2Frame(streamID: .rootStream, payload: .goAway(lastStreamID: .rootStream, errorCode: .http11Required, opaqueData: nil)) let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (channel, _) in - XCTAssertNil(closeError) - channel.closeFuture.whenFailure { closeError = $0 } + closeError.withLockedValue { closeError in + XCTAssertNil(closeError) + } + channel.closeFuture.whenFailure { error in + closeError.withLockedValue { closeError in + closeError = error + } + } // The channel won't see the goaway frame. return channel.pipeline.addHandler(FrameExpecter(expectedFrames: [frame])) } @@ -373,7 +392,9 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { // Let's open the stream up. XCTAssertNoThrow(try self.channel.writeInbound(frame)) self.activateStream(streamID) - XCTAssertNil(closeError) + closeError.withLockedValue { closeError in + XCTAssertNil(closeError) + } // Now we can send a GOAWAY frame. This will close the stream. XCTAssertNoThrow(try self.channel.writeInbound(goAwayFrame)) @@ -384,8 +405,10 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { (self.channel.eventLoop as! EmbeddedEventLoop).run() // At this stage the stream should be closed with the appropriate manufactured error code. - XCTAssertEqual(closeError as? NIOHTTP2Errors.StreamClosed, - NIOHTTP2Errors.StreamClosed(streamID: streamID, errorCode: .refusedStream)) + closeError.withLockedValue { closeError in + XCTAssertEqual(closeError as? NIOHTTP2Errors.StreamClosed, + NIOHTTP2Errors.StreamClosed(streamID: streamID, errorCode: .refusedStream)) + } XCTAssertNoThrow(try self.channel.finish()) } @@ -401,7 +424,7 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { XCTAssertThrowsError(try self.channel.writeInbound(dataFrame)) { error in XCTAssertEqual(streamID, (error as? NIOHTTP2Errors.NoSuchStream).map { $0.streamID }) } - + self.channel.assertNoFramesReceived() XCTAssertNoThrow(try self.channel.finish()) @@ -516,16 +539,18 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { 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 } + let closed = ManagedAtomic(false) + childChannel.close().whenComplete { _ in + closed.store(true, ordering: .sequentiallyConsistent) + } XCTAssertEqual(frameReceiver.flushedWrites.count, 1) frameReceiver.flushedWrites[0].assertRstStreamFrame(streamID: streamID, errorCode: .cancel) - XCTAssertFalse(closed) + XCTAssertFalse(closed.load(ordering: .sequentiallyConsistent)) // Now send the stream closed event. This will satisfy the close promise. let userEvent = StreamClosedEvent(streamID: streamID, reason: .cancel) self.channel.pipeline.fireUserInboundEventTriggered(userEvent) - XCTAssertTrue(closed) + XCTAssertTrue(closed.load(ordering: .sequentiallyConsistent)) XCTAssertNoThrow(try self.channel.finish()) } @@ -555,35 +580,35 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { 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 + let firstClosed = ManagedAtomic(false) + let secondClosed = ManagedAtomic(false) + let thirdClosed = ManagedAtomic(false) childChannel.close().whenComplete { _ in - XCTAssertFalse(firstClosed) - XCTAssertFalse(secondClosed) - XCTAssertFalse(thirdClosed) - firstClosed = true + XCTAssertFalse(firstClosed.load(ordering: .sequentiallyConsistent)) + XCTAssertFalse(secondClosed.load(ordering: .sequentiallyConsistent)) + XCTAssertFalse(thirdClosed.load(ordering: .sequentiallyConsistent)) + firstClosed.store(true, ordering: .sequentiallyConsistent) } childChannel.close().whenComplete { _ in - XCTAssertTrue(firstClosed) - XCTAssertFalse(secondClosed) - XCTAssertFalse(thirdClosed) - secondClosed = true + XCTAssertTrue(firstClosed.load(ordering: .sequentiallyConsistent)) + XCTAssertFalse(secondClosed.load(ordering: .sequentiallyConsistent)) + XCTAssertFalse(thirdClosed.load(ordering: .sequentiallyConsistent)) + secondClosed.store(true, ordering: .sequentiallyConsistent) } childChannel.close().whenComplete { _ in - XCTAssertTrue(firstClosed) - XCTAssertTrue(secondClosed) - XCTAssertFalse(thirdClosed) - thirdClosed = true + XCTAssertTrue(firstClosed.load(ordering: .sequentiallyConsistent)) + XCTAssertTrue(secondClosed.load(ordering: .sequentiallyConsistent)) + XCTAssertFalse(thirdClosed.load(ordering: .sequentiallyConsistent)) + thirdClosed.store(true, ordering: .sequentiallyConsistent) } XCTAssertEqual(frameReceiver.flushedWrites.count, 1) frameReceiver.flushedWrites[0].assertRstStreamFrame(streamID: streamID, errorCode: .cancel) - XCTAssertFalse(thirdClosed) + XCTAssertFalse(thirdClosed.load(ordering: .sequentiallyConsistent)) // Now send the stream closed event. This will satisfy the close promise. let userEvent = StreamClosedEvent(streamID: streamID, reason: .cancel) self.channel.pipeline.fireUserInboundEventTriggered(userEvent) - XCTAssertTrue(thirdClosed) + XCTAssertTrue(thirdClosed.load(ordering: .sequentiallyConsistent)) XCTAssertNoThrow(try self.channel.finish()) } @@ -612,16 +637,24 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { 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 } + let closeError = NIOLockedValueBox(nil) + childChannel.close().whenFailure { error in + closeError.withLockedValue { closeError in + closeError = error + } + } XCTAssertEqual(frameReceiver.flushedWrites.count, 1) frameReceiver.flushedWrites[0].assertRstStreamFrame(streamID: streamID, errorCode: .cancel) - XCTAssertNil(closeError) + closeError.withLockedValue { closeError in + XCTAssertNil(closeError) + } // Now send the stream closed event. This will fail the close promise. let userEvent = StreamClosedEvent(streamID: streamID, reason: .cancel) self.channel.pipeline.fireUserInboundEventTriggered(userEvent) - XCTAssertEqual(closeError as? NIOHTTP2Errors.StreamClosed, NIOHTTP2Errors.StreamClosed(streamID: streamID, errorCode: .cancel)) + closeError.withLockedValue { closeError in + XCTAssertEqual(closeError as? NIOHTTP2Errors.StreamClosed, NIOHTTP2Errors.StreamClosed(streamID: streamID, errorCode: .cancel)) + } XCTAssertNoThrow(try self.channel.finish()) } @@ -717,10 +750,10 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { // 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 } + let channelClosed = ManagedAtomic(false) + childChannel.closeFuture.whenComplete { _ in channelClosed.store(true, ordering: .sequentiallyConsistent) } XCTAssertEqual(writeRecorder.flushedWrites.count, 0) - XCTAssertFalse(channelClosed) + XCTAssertFalse(channelClosed.load(ordering: .sequentiallyConsistent)) setupCompletePromise.fail(MyError()) self.channel.assertNoFramesReceived() @@ -740,20 +773,21 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { XCTAssertEqual(frameRecorder.receivedFrames.count, 0) XCTAssertFalse(childChannel.isActive) XCTAssertEqual(writeRecorder.flushedWrites.count, 1) - XCTAssertFalse(channelClosed) + XCTAssertFalse(channelClosed.load(ordering: .sequentiallyConsistent)) (childChannel.eventLoop as! EmbeddedEventLoop).run() - XCTAssertTrue(channelClosed) + XCTAssertTrue(channelClosed.load(ordering: .sequentiallyConsistent)) XCTAssertNoThrow(try self.channel.finish()) } @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") - func testFlushingOneChannelDoesntFlushThemAll() throws { + func testFlushingOneChannelDoesntFlushThemAll() async throws { let writeTracker = FrameWriteRecorder() - var channels: [Channel] = [] + + let (channelsStream, channelsContinuation) = AsyncStream.makeStream(of: Channel.self) let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (channel, _) in - channels.append(channel) + channelsContinuation.yield(channel) return channel.eventLoop.makeSucceededFuture(()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(writeTracker).wait()) @@ -769,23 +803,25 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.writeInbound(frame)) self.activateStream(streamID) } - XCTAssertEqual(channels.count, 2) + + var streamChannelIterator = channelsStream.makeAsyncIterator() + let firstStreamChannel = await streamChannelIterator.next()! + let secondStreamChannel = await streamChannelIterator.next()! // 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, streamID) in [firstStreamID, secondStreamID].enumerated() { - let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders()))) - channels[idx].write(frame, promise: nil) - } + + firstStreamChannel.write(HTTP2Frame(streamID: firstStreamID, payload: .headers(.init(headers: HPACKHeaders()))), promise: nil) + secondStreamChannel.write(HTTP2Frame(streamID: secondStreamID, payload: .headers(.init(headers: HPACKHeaders()))), 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[0].flush() + firstStreamChannel.flush() XCTAssertEqual(writeTracker.flushedWrites.count, 1) // Now the other. - channels[1].flush() + secondStreamChannel.flush() XCTAssertEqual(writeTracker.flushedWrites.count, 2) XCTAssertNoThrow(try self.channel.finish()) @@ -793,9 +829,9 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testUnflushedWritesFailOnClose() throws { - var childChannel: Channel? = nil + let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (channel, _) in - childChannel = channel + childChannelPromise.succeed(channel) return channel.eventLoop.makeSucceededFuture(()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -805,28 +841,35 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders(), endStream: true))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) XCTAssertNotNil(channel) + let childChannel = try childChannelPromise.futureResult.wait() // We will now write a headers frame to the channel, but don't flush it. - var writeError: Error? = nil + let writeError = NIOLockedValueBox(nil) let responseFrame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders()))) - childChannel!.write(responseFrame).whenFailure { - writeError = $0 + childChannel.write(responseFrame).whenFailure { error in + writeError.withLockedValue { writeError in + writeError = error + } + } + writeError.withLockedValue { writeError in + XCTAssertNil(writeError) } - XCTAssertNil(writeError) // Now we're going to deliver a normal close to the stream. let userEvent = StreamClosedEvent(streamID: streamID, reason: nil) self.channel.pipeline.fireUserInboundEventTriggered(userEvent) - XCTAssertEqual(writeError as? ChannelError, ChannelError.eof) + writeError.withLockedValue { writeError in + XCTAssertEqual(writeError as? ChannelError, ChannelError.eof) + } XCTAssertNoThrow(try self.channel.finish()) } @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testUnflushedWritesFailOnError() throws { - var childChannel: Channel? = nil + let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (channel, _) in - childChannel = channel + childChannelPromise.succeed(channel) return channel.eventLoop.makeSucceededFuture(()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -836,28 +879,36 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders(), endStream: true))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) XCTAssertNotNil(channel) + let childChannel = try childChannelPromise.futureResult.wait() // We will now write a headers frame to the channel, but don't flush it. - var writeError: Error? = nil + let writeError = NIOLockedValueBox(nil) let responseFrame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders()))) - childChannel!.write(responseFrame).whenFailure { - writeError = $0 + childChannel.write(responseFrame).whenFailure { error in + writeError.withLockedValue { writeError in + writeError = error + } + } + writeError.withLockedValue { writeError in + XCTAssertNil(writeError) } - XCTAssertNil(writeError) // Now we're going to deliver a normal close to the stream. let userEvent = StreamClosedEvent(streamID: streamID, reason: .cancel) self.channel.pipeline.fireUserInboundEventTriggered(userEvent) - XCTAssertEqual(writeError as? NIOHTTP2Errors.StreamClosed, NIOHTTP2Errors.StreamClosed(streamID: streamID, errorCode: .cancel)) + + writeError.withLockedValue { writeError in + XCTAssertEqual(writeError as? NIOHTTP2Errors.StreamClosed, NIOHTTP2Errors.StreamClosed(streamID: streamID, errorCode: .cancel)) + } XCTAssertNoThrow(try self.channel.finish()) } @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testWritesFailOnClosedStreamChannels() throws { - var childChannel: Channel? = nil + let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (channel, _) in - childChannel = channel + childChannelPromise.succeed(channel) return channel.eventLoop.makeSucceededFuture(()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -872,23 +923,29 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { let userEvent = StreamClosedEvent(streamID: streamID, reason: nil) self.channel.pipeline.fireUserInboundEventTriggered(userEvent) + let childChannel = try childChannelPromise.futureResult.wait() + // We will now write a headers frame to the channel. This should fail immediately. - var writeError: Error? = nil + let writeError = NIOLockedValueBox(nil) let responseFrame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders()))) - childChannel!.write(responseFrame).whenFailure { - writeError = $0 + childChannel.write(responseFrame).whenFailure { error in + writeError.withLockedValue { writeError in + writeError = error + } + } + writeError.withLockedValue { writeError in + XCTAssertEqual(writeError as? ChannelError, ChannelError.ioOnClosedChannel) } - XCTAssertEqual(writeError as? ChannelError, ChannelError.ioOnClosedChannel) XCTAssertNoThrow(try self.channel.finish()) } @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testReadPullsInAllFrames() throws { - var childChannel: Channel? = nil + let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) let frameRecorder = InboundFrameRecorder() let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (channel, _) -> EventLoopFuture in - childChannel = channel + childChannelPromise.succeed(channel) // We're going to disable autoRead on this channel. return channel.getOption(ChannelOptions.autoRead).map { @@ -908,12 +965,13 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) + // Let's open a stream. let streamID = HTTP2StreamID(1) let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders()))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) self.activateStream(1) - XCTAssertNotNil(childChannel) + let childChannel = try childChannelPromise.futureResult.wait() // Now we're going to deliver 5 data frames for this stream. var buffer = self.channel.allocator.buffer(capacity: 12) @@ -927,7 +985,7 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { XCTAssertEqual(frameRecorder.receivedFrames.count, 0) // We'll call read() on the child channel. - childChannel!.read() + childChannel.read() // All frames should now have been delivered. XCTAssertEqual(frameRecorder.receivedFrames.count, 6) @@ -940,14 +998,13 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { } @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") - func testReadIsPerChannel() throws { + func testReadIsPerChannel() async throws { let firstStreamID = HTTP2StreamID(1) let secondStreamID = HTTP2StreamID(3) - var frameRecorders: [HTTP2StreamID: InboundFrameRecorder] = [:] - + let (channelsStream, channelsContinuation) = AsyncStream.makeStream(of: Channel.self) let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (channel, streamID) -> EventLoopFuture in let recorder = InboundFrameRecorder() - frameRecorders[streamID] = recorder + channelsContinuation.yield(channel) // Disable autoRead on the first channel. return channel.setOption(ChannelOptions.autoRead, value: streamID != firstStreamID).flatMap { @@ -964,11 +1021,18 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.writeInbound(frame)) self.activateStream(streamID) } - XCTAssertEqual(frameRecorders.count, 2) + + var streamChannelIterator = channelsStream.makeAsyncIterator() + let firstStreamChannel = await streamChannelIterator.next()! + let secondStreamChannel = await streamChannelIterator.next()! // Stream 1 should not have received a frame, stream 3 should. - XCTAssertEqual(frameRecorders[firstStreamID]!.receivedFrames.count, 0) - XCTAssertEqual(frameRecorders[secondStreamID]!.receivedFrames.count, 1) + try await firstStreamChannel.pipeline.handler(type: InboundFrameRecorder.self).map { recorder in + XCTAssertEqual(recorder.receivedFrames.count, 0) + }.get() + try await secondStreamChannel.pipeline.handler(type: InboundFrameRecorder.self).map { recorder in + XCTAssertEqual(recorder.receivedFrames.count, 1) + }.get() // Deliver a DATA frame to each stream, which should also have gone into stream 3 but not stream 1. var buffer = self.channel.allocator.buffer(capacity: 12) @@ -978,19 +1042,24 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.writeInbound(frame)) } + try await firstStreamChannel.pipeline.handler(type: InboundFrameRecorder.self).map { recorder in + XCTAssertEqual(recorder.receivedFrames.count, 0) + }.get() + // Stream 1 should not have received a frame, stream 3 should. - XCTAssertEqual(frameRecorders[firstStreamID]!.receivedFrames.count, 0) - XCTAssertEqual(frameRecorders[secondStreamID]!.receivedFrames.count, 2) + try await secondStreamChannel.pipeline.handler(type: InboundFrameRecorder.self).map { recorder in + XCTAssertEqual(recorder.receivedFrames.count, 2) + }.get() XCTAssertNoThrow(try self.channel.finish()) } @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testReadWillCauseAutomaticFrameDelivery() throws { - var childChannel: Channel? = nil + let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) let frameRecorder = InboundFrameRecorder() let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (channel, _) -> EventLoopFuture in - childChannel = channel + childChannelPromise.succeed(channel) // We're going to disable autoRead on this channel. return channel.setOption(ChannelOptions.autoRead, value: false).flatMap { @@ -1006,17 +1075,19 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders()))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) self.activateStream(streamID) - XCTAssertNotNil(childChannel) + + + let childChannel = try childChannelPromise.futureResult.wait() // This stream should have seen no frames. XCTAssertEqual(frameRecorder.receivedFrames.count, 0) // Call read, the header frame will come through. - childChannel!.read() + childChannel.read() XCTAssertEqual(frameRecorder.receivedFrames.count, 1) // Call read again, nothing happens. - childChannel!.read() + childChannel.read() XCTAssertEqual(frameRecorder.receivedFrames.count, 1) // Now deliver a data frame. @@ -1037,11 +1108,11 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testReadWithNoPendingDataCausesReadOnParentChannel() throws { - var childChannel: Channel? = nil + let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) let readCounter = ReadCounter() let frameRecorder = InboundFrameRecorder() let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (channel, _) -> EventLoopFuture in - childChannel = channel + childChannelPromise.succeed(channel) // We're going to disable autoRead on this channel. return channel.setOption(ChannelOptions.autoRead, value: false).flatMap { @@ -1058,23 +1129,31 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders()))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) self.activateStream(streamID) - XCTAssertNotNil(childChannel) + + + let childChannel = try childChannelPromise.futureResult.wait() // This stream should have seen no frames. XCTAssertEqual(frameRecorder.receivedFrames.count, 0) // There should be no calls to read. - XCTAssertEqual(readCounter.readCount, 0) + readCounter.readCount.withLockedValue { readCount in + XCTAssertEqual(readCount, 0) + } // Call read, the header frame will come through. No calls to read on the parent stream. - childChannel!.read() + childChannel.read() XCTAssertEqual(frameRecorder.receivedFrames.count, 1) - XCTAssertEqual(readCounter.readCount, 0) + readCounter.readCount.withLockedValue { readCount in + XCTAssertEqual(readCount, 0) + } // Call read again, read is called on the parent stream. No frames delivered. - childChannel!.read() + childChannel.read() XCTAssertEqual(frameRecorder.receivedFrames.count, 1) - XCTAssertEqual(readCounter.readCount, 1) + readCounter.readCount.withLockedValue { readCount in + XCTAssertEqual(readCount, 1) + } // Now deliver a data frame. var buffer = self.channel.allocator.buffer(capacity: 12) @@ -1084,33 +1163,41 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { // This frame should have been immediately delivered. No extra call to read. XCTAssertEqual(frameRecorder.receivedFrames.count, 2) - XCTAssertEqual(readCounter.readCount, 1) + readCounter.readCount.withLockedValue { readCount in + XCTAssertEqual(readCount, 1) + } // Another call to read issues a read to the parent stream. - childChannel!.read() + childChannel.read() XCTAssertEqual(frameRecorder.receivedFrames.count, 2) - XCTAssertEqual(readCounter.readCount, 2) + readCounter.readCount.withLockedValue { readCount in + XCTAssertEqual(readCount, 2) + } // Another call to read, this time does not issue a read to the parent stream. - childChannel!.read() + childChannel.read() XCTAssertEqual(frameRecorder.receivedFrames.count, 2) - XCTAssertEqual(readCounter.readCount, 2) + readCounter.readCount.withLockedValue { readCount in + XCTAssertEqual(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) + readCounter.readCount.withLockedValue { readCount in + XCTAssertEqual(readCount, 2) + } XCTAssertNoThrow(try self.channel.finish()) } @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testHandlersAreRemovedOnClosure() throws { - var handlerRemoved = false + let handlerRemoved = ManagedAtomic(false) let handlerRemovedPromise: EventLoopPromise = self.channel.eventLoop.makePromise() - handlerRemovedPromise.futureResult.whenComplete { _ in handlerRemoved = true } + handlerRemovedPromise.futureResult.whenComplete { _ in handlerRemoved.store(true, ordering: .sequentiallyConsistent) } let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (channel, _) in return channel.pipeline.addHandler(HandlerRemovedHandler(removedPromise: handlerRemovedPromise)) @@ -1123,25 +1210,25 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.writeInbound(frame)) // No handlerRemoved so far. - XCTAssertFalse(handlerRemoved) + XCTAssertFalse(handlerRemoved.load(ordering: .sequentiallyConsistent)) // Now we send the channel a clean exit. let event = StreamClosedEvent(streamID: streamID, reason: nil) self.channel.pipeline.fireUserInboundEventTriggered(event) - XCTAssertFalse(handlerRemoved) + XCTAssertFalse(handlerRemoved.load(ordering: .sequentiallyConsistent)) // The handlers will only be removed after we spin the loop. (self.channel.eventLoop as! EmbeddedEventLoop).run() - XCTAssertTrue(handlerRemoved) + XCTAssertTrue(handlerRemoved.load(ordering: .sequentiallyConsistent)) XCTAssertNoThrow(try self.channel.finish()) } @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testHandlersAreRemovedOnClosureWithError() throws { - var handlerRemoved = false + let handlerRemoved = ManagedAtomic(false) let handlerRemovedPromise: EventLoopPromise = self.channel.eventLoop.makePromise() - handlerRemovedPromise.futureResult.whenComplete { _ in handlerRemoved = true } + handlerRemovedPromise.futureResult.whenComplete { _ in handlerRemoved.store(true, ordering: .sequentiallyConsistent) } let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (channel, _) in return channel.pipeline.addHandler(HandlerRemovedHandler(removedPromise: handlerRemovedPromise)) @@ -1154,16 +1241,16 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.writeInbound(frame)) // No handlerRemoved so far. - XCTAssertFalse(handlerRemoved) + XCTAssertFalse(handlerRemoved.load(ordering: .sequentiallyConsistent)) // Now we send the channel a clean exit. let event = StreamClosedEvent(streamID: streamID, reason: .cancel) self.channel.pipeline.fireUserInboundEventTriggered(event) - XCTAssertFalse(handlerRemoved) + XCTAssertFalse(handlerRemoved.load(ordering: .sequentiallyConsistent)) // The handlers will only be removed after we spin the loop. (self.channel.eventLoop as! EmbeddedEventLoop).run() - XCTAssertTrue(handlerRemoved) + XCTAssertTrue(handlerRemoved.load(ordering: .sequentiallyConsistent)) XCTAssertNoThrow(try self.channel.finish()) } @@ -1171,40 +1258,44 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testCreatingOutboundChannel() throws { let configurePromise: EventLoopPromise = self.channel.eventLoop.makePromise() - var createdChannelCount = 0 - var configuredChannelCount = 0 - var streamIDs = Array() - let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (_, _) in + let createdChannelCount = ManagedAtomic(0) + let configuredChannelCount = ManagedAtomic(0) + let streamIDs = NIOLockedValueBox(Array()) + let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (channel, _) in XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) + return channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) for _ in 0..<3 { let channelPromise: EventLoopPromise = self.channel.eventLoop.makePromise() + multiplexer.createStreamChannel(promise: channelPromise) { (channel, streamID) in - createdChannelCount += 1 - streamIDs.append(streamID) + createdChannelCount.wrappingIncrement(ordering: .sequentiallyConsistent) + streamIDs.withLockedValue { streamIDs in + streamIDs.append(streamID) + } return configurePromise.futureResult } + channelPromise.futureResult.whenSuccess { _ in - configuredChannelCount += 1 + configuredChannelCount.wrappingIncrement(ordering: .sequentiallyConsistent) } } - XCTAssertEqual(createdChannelCount, 0) - XCTAssertEqual(configuredChannelCount, 0) - XCTAssertEqual(streamIDs.count, 0) - (self.channel.eventLoop as! EmbeddedEventLoop).run() - XCTAssertEqual(createdChannelCount, 3) - XCTAssertEqual(configuredChannelCount, 0) - XCTAssertEqual(streamIDs, [2, 4, 6].map { HTTP2StreamID($0) }) + XCTAssertEqual(createdChannelCount.load(ordering: .sequentiallyConsistent), 3) + XCTAssertEqual(configuredChannelCount.load(ordering: .sequentiallyConsistent), 0) + streamIDs.withLockedValue { streamIDs in + XCTAssertEqual(streamIDs, [2, 4, 6].map { HTTP2StreamID($0) }) + } configurePromise.succeed(()) - XCTAssertEqual(createdChannelCount, 3) - XCTAssertEqual(configuredChannelCount, 3) - XCTAssertEqual(streamIDs, [2, 4, 6].map { HTTP2StreamID($0) }) + XCTAssertEqual(createdChannelCount.load(ordering: .sequentiallyConsistent), 3) + XCTAssertEqual(configuredChannelCount.load(ordering: .sequentiallyConsistent), 3) + streamIDs.withLockedValue { streamIDs in + XCTAssertEqual(streamIDs, [2, 4, 6].map { HTTP2StreamID($0) }) + } XCTAssertNoThrow(try self.channel.finish()) } @@ -1212,40 +1303,42 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testCreatingOutboundChannelClient() throws { let configurePromise: EventLoopPromise = self.channel.eventLoop.makePromise() - var createdChannelCount = 0 - var configuredChannelCount = 0 - var streamIDs = Array() - let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.channel) { (_, _) in + let createdChannelCount = ManagedAtomic(0) + let configuredChannelCount = ManagedAtomic(0) + let streamIDs = NIOLockedValueBox(Array()) + let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.channel) { (channel, _) in XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) + return channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) for _ in 0..<3 { let channelPromise: EventLoopPromise = self.channel.eventLoop.makePromise() multiplexer.createStreamChannel(promise: channelPromise) { (channel, streamID) in - createdChannelCount += 1 - streamIDs.append(streamID) + createdChannelCount.wrappingIncrement(ordering: .sequentiallyConsistent) + streamIDs.withLockedValue { streamIDs in + streamIDs.append(streamID) + } return configurePromise.futureResult } channelPromise.futureResult.whenSuccess { _ in - configuredChannelCount += 1 + configuredChannelCount.wrappingIncrement(ordering: .sequentiallyConsistent) } } - XCTAssertEqual(createdChannelCount, 0) - XCTAssertEqual(configuredChannelCount, 0) - XCTAssertEqual(streamIDs.count, 0) - (self.channel.eventLoop as! EmbeddedEventLoop).run() - XCTAssertEqual(createdChannelCount, 3) - XCTAssertEqual(configuredChannelCount, 0) - XCTAssertEqual(streamIDs, [1, 3, 5].map { HTTP2StreamID($0) }) + XCTAssertEqual(createdChannelCount.load(ordering: .sequentiallyConsistent), 3) + XCTAssertEqual(configuredChannelCount.load(ordering: .sequentiallyConsistent), 0) + streamIDs.withLockedValue { streamIDs in + XCTAssertEqual(streamIDs, [1, 3, 5].map { HTTP2StreamID($0) }) + } configurePromise.succeed(()) - XCTAssertEqual(createdChannelCount, 3) - XCTAssertEqual(configuredChannelCount, 3) - XCTAssertEqual(streamIDs, [1, 3, 5].map { HTTP2StreamID($0) }) + XCTAssertEqual(createdChannelCount.load(ordering: .sequentiallyConsistent), 3) + XCTAssertEqual(configuredChannelCount.load(ordering: .sequentiallyConsistent), 3) + streamIDs.withLockedValue { streamIDs in + XCTAssertEqual(streamIDs, [1, 3, 5].map { HTTP2StreamID($0) }) + } XCTAssertNoThrow(try self.channel.finish()) } @@ -1254,27 +1347,30 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { func testWritesOnCreatedChannelAreDelayed() throws { let configurePromise: EventLoopPromise = self.channel.eventLoop.makePromise() let writeRecorder = FrameWriteRecorder() - var childChannel: Channel? = nil - var childStreamID: HTTP2StreamID? = nil + let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) + let childStreamIDPromise = self.channel.eventLoop.makePromise(of: HTTP2StreamID.self) XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) - let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (_, _) in + let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (channel, _) in XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) + return channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(writeRecorder).wait()) XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) multiplexer.createStreamChannel(promise: nil) { (channel, streamID) in - childChannel = channel - childStreamID = streamID + childChannelPromise.succeed(channel) + childStreamIDPromise.succeed(streamID) return configurePromise.futureResult } (self.channel.eventLoop as! EmbeddedEventLoop).run() - XCTAssertNotNil(childChannel) - XCTAssertNotNil(childStreamID) - childChannel!.writeAndFlush(HTTP2Frame(streamID: childStreamID!, payload: .headers(.init(headers: HPACKHeaders()))), promise: nil) + + let childChannel = try childChannelPromise.futureResult.wait() + let childStreamID = try childStreamIDPromise.futureResult.wait() + + childChannel.writeAndFlush(HTTP2Frame(streamID: childStreamID, payload: .headers(.init(headers: HPACKHeaders()))), promise: nil) + XCTAssertEqual(writeRecorder.flushedWrites.count, 0) configurePromise.succeed(()) @@ -1287,28 +1383,41 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testWritesAreCancelledOnFailingInitializer() throws { let configurePromise: EventLoopPromise = self.channel.eventLoop.makePromise() - var childChannel: Channel? = nil - var childStreamID: HTTP2StreamID? = nil + let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) + let childStreamIDPromise = self.channel.eventLoop.makePromise(of: HTTP2StreamID.self) - let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (_, _) in + let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (channel, _) in XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) + return channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) multiplexer.createStreamChannel(promise: nil) { (channel, streamID) in - childChannel = channel - childStreamID = streamID + childChannelPromise.succeed(channel) + childStreamIDPromise.succeed(streamID) return configurePromise.futureResult } (self.channel.eventLoop as! EmbeddedEventLoop).run() - var writeError: Error? = nil - childChannel!.writeAndFlush(HTTP2Frame(streamID: childStreamID!, payload: .headers(.init(headers: HPACKHeaders())))).whenFailure { writeError = $0 } - XCTAssertNil(writeError) + let childChannel = try childChannelPromise.futureResult.wait() + let childStreamID = try childStreamIDPromise.futureResult.wait() + + let writeError = NIOLockedValueBox(nil) + + childChannel.writeAndFlush(HTTP2Frame(streamID: childStreamID, payload: .headers(.init(headers: HPACKHeaders())))).whenFailure { error in + writeError.withLockedValue { writeError in + writeError = error + } + } + + writeError.withLockedValue { writeError in + XCTAssertNil(writeError) + } configurePromise.fail(MyError()) - XCTAssertNotNil(writeError) - XCTAssertTrue(writeError is MyError) + writeError.withLockedValue { writeError in + XCTAssertNotNil(writeError) + XCTAssertTrue(writeError is MyError) + } XCTAssertNoThrow(try self.channel.finish()) } @@ -1318,9 +1427,9 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { let configurePromise: EventLoopPromise = self.channel.eventLoop.makePromise() let writeRecorder = FrameWriteRecorder() - let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (_, _) in + let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (channel, _) in XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) + return channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(writeRecorder).wait()) XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -1337,60 +1446,60 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testCreatedChildChannelDoesNotActivateEarly() throws { - var activated = false + let activated = ManagedAtomic(false) let activePromise: EventLoopPromise = self.channel.eventLoop.makePromise() - let activeRecorder = ActiveHandler(activatedPromise: activePromise) activePromise.futureResult.map { - activated = true + activated.store(true, ordering: .sequentiallyConsistent) }.whenFailure { (_: Error) in XCTFail("Activation promise must not fail") } - let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (_, _) in + let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (channel, _) in XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) + return channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) multiplexer.createStreamChannel(promise: nil) { (channel, streamID) in + let activeRecorder = ActiveHandler(activatedPromise: activePromise) return channel.pipeline.addHandler(activeRecorder) } (self.channel.eventLoop as! EmbeddedEventLoop).run() - XCTAssertFalse(activated) + XCTAssertFalse(activated.load(ordering: .sequentiallyConsistent)) XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) - XCTAssertTrue(activated) + XCTAssertTrue(activated.load(ordering: .sequentiallyConsistent)) XCTAssertNoThrow(try self.channel.finish()) } @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testCreatedChildChannelActivatesIfParentIsActive() throws { - var activated = false + let activated = ManagedAtomic(false) let activePromise: EventLoopPromise = self.channel.eventLoop.makePromise() - let activeRecorder = ActiveHandler(activatedPromise: activePromise) activePromise.futureResult.map { - activated = true + activated.store(true, ordering: .sequentiallyConsistent) }.whenFailure { (_: Error) in XCTFail("Activation promise must not fail") } - let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (_, _) in + let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (channel, _) in XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) + return channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 8765)).wait()) - XCTAssertFalse(activated) + XCTAssertFalse(activated.load(ordering: .sequentiallyConsistent)) multiplexer.createStreamChannel(promise: nil) { (channel, streamID) in + let activeRecorder = ActiveHandler(activatedPromise: activePromise) return channel.pipeline.addHandler(activeRecorder) } (self.channel.eventLoop as! EmbeddedEventLoop).run() - XCTAssertTrue(activated) + XCTAssertTrue(activated.load(ordering: .sequentiallyConsistent)) XCTAssertNoThrow(try self.channel.finish()) } @@ -1399,28 +1508,28 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { func testInitiatedChildChannelActivates() throws { XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) - var activated = false + let activated = ManagedAtomic(false) let activePromise: EventLoopPromise = self.channel.eventLoop.makePromise() - let activeRecorder = ActiveHandler(activatedPromise: activePromise) activePromise.futureResult.map { - activated = true + activated.store(true, ordering: .sequentiallyConsistent) }.whenFailure { (_: Error) in XCTFail("Activation promise must not fail") } let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (channel, _) in + let activeRecorder = ActiveHandler(activatedPromise: activePromise) return channel.pipeline.addHandler(activeRecorder) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) self.channel.pipeline.fireChannelActive() // Open a new stream. - XCTAssertFalse(activated) + XCTAssertFalse(activated.load(ordering: .sequentiallyConsistent)) let streamID = HTTP2StreamID(1) let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders()))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) - XCTAssertTrue(activated) + XCTAssertTrue(activated.load(ordering: .sequentiallyConsistent)) XCTAssertNoThrow(try self.channel.finish()) } @@ -1440,46 +1549,48 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { func testMultiplexerForwardsActiveToParent() throws { self.channel.addNoOpMultiplexer(mode: .client) - var didActivate = false + let didActivate = ManagedAtomic(false) let activePromise = self.channel.eventLoop.makePromise(of: Void.self) activePromise.futureResult.whenSuccess { - didActivate = true + didActivate.store(true, ordering: .sequentiallyConsistent) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(ActiveHandler(activatedPromise: activePromise)).wait()) XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/nothing")).wait()) - XCTAssertTrue(didActivate) - + XCTAssertTrue(didActivate.load(ordering: .sequentiallyConsistent)) + XCTAssertNoThrow(try self.channel.finish()) } @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testCreatedChildChannelCanBeClosedImmediately() throws { - var closed = false + let closed = ManagedAtomic(false) let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.channel) { (channel, _) in XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) + return channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) - XCTAssertFalse(closed) + XCTAssertFalse(closed.load(ordering: .sequentiallyConsistent)) multiplexer.createStreamChannel(promise: nil) { (channel, streamID) in - channel.close().whenComplete { _ in closed = true } + channel.close().whenComplete { _ in + closed.store(true, ordering: .sequentiallyConsistent) + } return channel.eventLoop.makeSucceededFuture(()) } self.channel.embeddedEventLoop.run() - XCTAssertTrue(closed) + XCTAssertTrue(closed.load(ordering: .sequentiallyConsistent)) XCTAssertNoThrow(XCTAssertTrue(try self.channel.finish().isClean)) } @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testCreatedChildChannelCanBeClosedBeforeWritingHeaders() throws { - var closed = false + let closed = ManagedAtomic(false) let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.channel) { (channel, _) in XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) + return channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -1490,48 +1601,52 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { self.channel.embeddedEventLoop.run() let child = try assertNoThrowWithValue(channelPromise.futureResult.wait()) - child.closeFuture.whenComplete { _ in closed = true } + child.closeFuture.whenComplete { _ in + closed.store(true, ordering: .sequentiallyConsistent) + } - XCTAssertFalse(closed) + XCTAssertFalse(closed.load(ordering: .sequentiallyConsistent)) child.close(promise: nil) self.channel.embeddedEventLoop.run() - XCTAssertTrue(closed) + XCTAssertTrue(closed.load(ordering: .sequentiallyConsistent)) XCTAssertNoThrow(XCTAssertTrue(try self.channel.finish().isClean)) } @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testCreatedChildChannelCanBeClosedImmediatelyWhenBaseIsActive() throws { - var closed = false + 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 multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.channel) { (channel, _) in XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) + return channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) - XCTAssertFalse(closed) + XCTAssertFalse(closed.load(ordering: .sequentiallyConsistent)) multiplexer.createStreamChannel(promise: nil) { (channel, streamID) in - channel.close().whenComplete { _ in closed = true } + channel.close().whenComplete { _ in + closed.store(true, ordering: .sequentiallyConsistent) + } return channel.eventLoop.makeSucceededFuture(()) } self.channel.embeddedEventLoop.run() - XCTAssertTrue(closed) + XCTAssertTrue(closed.load(ordering: .sequentiallyConsistent)) XCTAssertNoThrow(XCTAssertTrue(try self.channel.finish().isClean)) } @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testCreatedChildChannelCanBeClosedBeforeWritingHeadersWhenBaseIsActive() throws { - var closed = false + 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 multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.channel) { (channel, _) in XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) + return channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -1542,12 +1657,14 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { self.channel.embeddedEventLoop.run() let child = try assertNoThrowWithValue(channelPromise.futureResult.wait()) - child.closeFuture.whenComplete { _ in closed = true } + child.closeFuture.whenComplete { _ in + closed.store(true, ordering: .sequentiallyConsistent) + } - XCTAssertFalse(closed) + XCTAssertFalse(closed.load(ordering: .sequentiallyConsistent)) child.close(promise: nil) self.channel.embeddedEventLoop.run() - XCTAssertTrue(closed) + XCTAssertTrue(closed.load(ordering: .sequentiallyConsistent)) XCTAssertNoThrow(XCTAssertTrue(try self.channel.finish().isClean)) } @@ -1602,7 +1719,9 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) XCTAssertEqual(frameRecorder.receivedFrames.count, 0) - XCTAssertEqual(readCompleteCounter.readCompleteCount, 0) + readCompleteCounter.readCompleteCount.withLockedValue { readCompleteCount in + XCTAssertEqual(readCompleteCount, 0) + } // Wake up and activate the stream. let requestHeaders = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) @@ -1612,7 +1731,9 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { self.channel.embeddedEventLoop.run() XCTAssertEqual(frameRecorder.receivedFrames.count, 1) - XCTAssertEqual(readCompleteCounter.readCompleteCount, 1) + readCompleteCounter.readCompleteCount.withLockedValue { readCompleteCount in + XCTAssertEqual(readCompleteCount, 1) + } // Now we're going to send 9 data frames. var requestData = self.channel.allocator.buffer(capacity: 1024) @@ -1625,19 +1746,25 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { // We should have 1 read (the HEADERS), and zero read completes. XCTAssertEqual(frameRecorder.receivedFrames.count, 1) - XCTAssertEqual(readCompleteCounter.readCompleteCount, 1) + readCompleteCounter.readCompleteCount.withLockedValue { readCompleteCount in + XCTAssertEqual(readCompleteCount, 1) + } // Fire read complete on the parent and it'll propagate to the child, also firing the reads.. self.channel.pipeline.fireChannelReadComplete() // We should have 10 reads, and one read complete. XCTAssertEqual(frameRecorder.receivedFrames.count, 10) - XCTAssertEqual(readCompleteCounter.readCompleteCount, 2) + readCompleteCounter.readCompleteCount.withLockedValue { readCompleteCount in + XCTAssertEqual(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) + readCompleteCounter.readCompleteCount.withLockedValue { readCompleteCount in + XCTAssertEqual(readCompleteCount, 2) + } } @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") @@ -1658,7 +1785,9 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) XCTAssertEqual(frameRecorder.receivedFrames.count, 0) - XCTAssertEqual(readCompleteCounter.readCompleteCount, 0) + readCompleteCounter.readCompleteCount.withLockedValue { readCompleteCount in + XCTAssertEqual(readCompleteCount, 0) + } // Wake up and activate the streams. let requestHeaders = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) @@ -1671,12 +1800,16 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { self.channel.embeddedEventLoop.run() XCTAssertEqual(frameRecorder.receivedFrames.count, 3) - XCTAssertEqual(readCompleteCounter.readCompleteCount, 3) + readCompleteCounter.readCompleteCount.withLockedValue { readCompleteCount in + XCTAssertEqual(readCompleteCount, 3) + } // Firing in readComplete does not cause a readComplete, as no new frames were delivered. self.channel.pipeline.fireChannelReadComplete() XCTAssertEqual(frameRecorder.receivedFrames.count, 3) - XCTAssertEqual(readCompleteCounter.readCompleteCount, 3) + readCompleteCounter.readCompleteCount.withLockedValue { readCompleteCount in + XCTAssertEqual(readCompleteCount, 3) + } // Now we're going to send a data frame on stream 1. var requestData = self.channel.allocator.buffer(capacity: 1024) @@ -1687,7 +1820,9 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { // We should have 3 reads, and 3 read completes. We don't actually get this frame yet, because // we do not do a "fast-delivery" path. XCTAssertEqual(frameRecorder.receivedFrames.count, 3) - XCTAssertEqual(readCompleteCounter.readCompleteCount, 3) + readCompleteCounter.readCompleteCount.withLockedValue { readCompleteCount in + XCTAssertEqual(readCompleteCount, 3) + } // Fire read complete on the parent and it'll propagate to the child, but only to the one // that saw a frame. @@ -1695,12 +1830,16 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { // We should have 4 reads, and 4 read completes. XCTAssertEqual(frameRecorder.receivedFrames.count, 4) - XCTAssertEqual(readCompleteCounter.readCompleteCount, 4) + readCompleteCounter.readCompleteCount.withLockedValue { readCompleteCount in + XCTAssertEqual(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) + readCompleteCounter.readCompleteCount.withLockedValue { readCompleteCount in + XCTAssertEqual(readCompleteCount, 4) + } } @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") @@ -1708,9 +1847,9 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.channel, outboundBufferSizeHighWatermark: 100, - outboundBufferSizeLowWatermark: 50) { (_, _) in + outboundBufferSizeLowWatermark: 50) { (channel, _) in XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) + return channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -1759,9 +1898,9 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testMultiplexerModifiesStreamChannelWritabilityBasedOnParentChannelWritability() throws { - let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.channel) { (_, _) in + let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.channel) { (channel, _) in XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) + return channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -1808,9 +1947,9 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.channel, outboundBufferSizeHighWatermark: 100, - outboundBufferSizeLowWatermark: 50) { (_, _) in + outboundBufferSizeLowWatermark: 50) { (channel, _) in XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) + return channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -1873,9 +2012,9 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.channel, outboundBufferSizeHighWatermark: 100, - outboundBufferSizeLowWatermark: 50) { (_, _) in + outboundBufferSizeLowWatermark: 50) { (channel, _) in XCTFail("Must not be called") - return self.channel.eventLoop.makeFailedFuture(MyError()) + return channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -1933,7 +2072,7 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { typealias InboundOut = Element typealias OutboundIn = Element typealias OutboundOut = Element - + let elementsToBufferCount: Int = 1 var bufferedElements: CircularBuffer = [] @@ -1941,29 +2080,29 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { while let bufferedElement = bufferedElements.popFirst() { context.fireChannelRead(wrapInboundOut(bufferedElement)) } - + context.read() } - + func channelRead(context: ChannelHandlerContext, data: NIOAny) { bufferedElements.append(unwrapInboundIn(data)) - + if bufferedElements.count > elementsToBufferCount { context.fireChannelRead(wrapInboundOut(bufferedElements.removeFirst())) } } } - + XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) let streamID = HTTP2StreamID(1) let headerFrame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders()))) let payloadBuffer = channel.allocator.buffer(capacity: 0) let dataFrame = HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(payloadBuffer)))) - + let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in channel.pipeline.addHandler(FramePayloadExpecter(expectedPayload: [headerFrame.payload, dataFrame.payload])) } - + XCTAssertNoThrow(try self.channel.pipeline.addHandler(BufferingChannelHandler()).wait()) XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) diff --git a/Tests/NIOHTTP2Tests/OutboundFlowControlBufferTests.swift b/Tests/NIOHTTP2Tests/OutboundFlowControlBufferTests.swift index 2865eff..82ad6ed 100644 --- a/Tests/NIOHTTP2Tests/OutboundFlowControlBufferTests.swift +++ b/Tests/NIOHTTP2Tests/OutboundFlowControlBufferTests.swift @@ -13,6 +13,7 @@ //===----------------------------------------------------------------------===// import XCTest +import Atomics import NIOCore import NIOEmbedded import NIOHTTP1 @@ -162,32 +163,32 @@ class OutboundFlowControlBufferTests: XCTestCase { self.buffer.streamCreated(streamOne, initialWindowSize: 15) // We send a large DATA frame here. - var frameWritten = false + let frameWritten = ManagedAtomic(false) let framePromise: EventLoopPromise = self.loop.makePromise() framePromise.futureResult.map { - frameWritten = true + frameWritten.store(true, ordering: .sequentiallyConsistent) }.whenFailure { XCTFail("Unexpected write failure: \($0)") } var frame = self.createDataFrame(streamOne, byteBufferSize: 50, endStream: true) XCTAssertNoThrow(try self.buffer.processOutboundFrame(frame, promise: framePromise).assertNothing()) - XCTAssertFalse(frameWritten) + XCTAssertFalse(frameWritten.load(ordering: .sequentiallyConsistent)) // Flush out the first frame. self.buffer.flushReceived() self.receivedFrames().assertFramesMatch([frame.sliceDataFrame(length: 15)]) - XCTAssertFalse(frameWritten) + XCTAssertFalse(frameWritten.load(ordering: .sequentiallyConsistent)) // Open the window, we get the second frame. self.buffer.updateWindowOfStream(streamOne, newSize: 34) self.receivedFrames().assertFramesMatch([frame.sliceDataFrame(length: 34)]) - XCTAssertFalse(frameWritten) + XCTAssertFalse(frameWritten.load(ordering: .sequentiallyConsistent)) // If we open again, we get the final frame, with endStream set. self.buffer.updateWindowOfStream(streamOne, newSize: 200) self.receivedFrames().assertFramesMatch([frame]) - XCTAssertTrue(frameWritten) + XCTAssertTrue(frameWritten.load(ordering: .sequentiallyConsistent)) } func testInterlacingWithHeaders() { diff --git a/Tests/NIOHTTP2Tests/SimpleClientServerFramePayloadStreamTests.swift b/Tests/NIOHTTP2Tests/SimpleClientServerFramePayloadStreamTests.swift index cb71170..3526867 100644 --- a/Tests/NIOHTTP2Tests/SimpleClientServerFramePayloadStreamTests.swift +++ b/Tests/NIOHTTP2Tests/SimpleClientServerFramePayloadStreamTests.swift @@ -13,6 +13,7 @@ //===----------------------------------------------------------------------===// import XCTest +import NIOConcurrencyHelpers import NIOCore import NIOEmbedded import NIOHPACK @@ -148,7 +149,7 @@ final class ClosedEventVsFrameOrderingHandler: ChannelInboundHandler { let frame = self.unwrapInboundIn(data) switch (frame.payload, frame.streamID) { case (.rstStream, self.targetStreamID), - (.goAway(_, _, _), .rootStream): + (.goAway(_, _, _), .rootStream): XCTAssertFalse(self.seenFrame) XCTAssertFalse(self.seenEvent) self.seenFrame = true @@ -200,7 +201,7 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { func basicHTTP2Connection(clientSettings: HTTP2Settings = nioDefaultSettings, serverSettings: HTTP2Settings = nioDefaultSettings, maximumBufferedControlFrames: Int = 10000, - withMultiplexerCallback multiplexerCallback: ((Channel) -> EventLoopFuture)? = nil) throws { + withMultiplexerCallback multiplexerCallback: NIOChannelInitializer? = nil) throws { XCTAssertNoThrow(try self.clientChannel.pipeline.addHandler(NIOHTTP2Handler(mode: .client, initialSettings: clientSettings, maximumBufferedControlFrames: maximumBufferedControlFrames)).wait()) @@ -1369,27 +1370,30 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { let clientStreamID = HTTP2StreamID(1) let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: headers, endStream: false))) - var promiseResults: [Bool?] = Array(repeatElement(nil as Bool?, count: 5)) + let writeCount = 5 self.clientChannel.write(reqFrame, promise: nil) let bodyFrame = HTTP2Frame(streamID: clientStreamID, payload: .data(.init(data: .byteBuffer(ByteBufferAllocator().buffer(capacity: 0))))) - for index in promiseResults.indices { - self.clientChannel.write(bodyFrame).map { - promiseResults[index] = true - }.whenFailure { - XCTAssertEqual($0 as? ChannelError, ChannelError.ioOnClosedChannel) - promiseResults[index] = false - } - } - XCTAssertEqual(promiseResults, [nil, nil, nil, nil, nil]) + let futures = (0 ..< writeCount).map { _ in + self.clientChannel.write(bodyFrame) + } // Close the channel. self.clientChannel.close(promise: nil) self.clientChannel.embeddedEventLoop.run() - // The promises should be succeeded. - XCTAssertEqual(promiseResults, [false, false, false, false, false]) + let promiseResults = try EventLoopFuture.whenAllComplete(futures, on: self.clientChannel.eventLoop).wait() + + for result in promiseResults { + switch result { + case .success: + XCTFail() + case .failure(let error): + XCTAssertEqual(error as? ChannelError, ChannelError.ioOnClosedChannel) + } + } + XCTAssertNoThrow(try self.serverChannel.finish()) } @@ -1831,6 +1835,7 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { 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. @@ -1861,7 +1866,7 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { let reqFrame = HTTP2Frame.FramePayload.headers(.init(headers: headers)) channel.write(reqFrame, promise: nil) - var requestBody = self.clientChannel.allocator.buffer(capacity: 65535) + var requestBody = channel.allocator.buffer(capacity: 65535) requestBody.writeBytes(Array(repeating: UInt8(0x04), count: 65535)) // Now prepare the large body. We need END_STREAM set. diff --git a/Tests/NIOHTTP2Tests/SimpleClientServerInlineStreamMultiplexerTests.swift b/Tests/NIOHTTP2Tests/SimpleClientServerInlineStreamMultiplexerTests.swift index 6a2feb5..c0f2288 100644 --- a/Tests/NIOHTTP2Tests/SimpleClientServerInlineStreamMultiplexerTests.swift +++ b/Tests/NIOHTTP2Tests/SimpleClientServerInlineStreamMultiplexerTests.swift @@ -189,7 +189,7 @@ class SimpleClientServerInlineStreamMultiplexerTests: XCTestCase { // 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) + var responseBody = channel.allocator.buffer(capacity: 65535) responseBody.writeBytes(Array(repeating: UInt8(0x04), count: 65535)) let respFramePayload = HTTP2Frame.FramePayload.headers(.init(headers: responseHeaders)) @@ -252,7 +252,7 @@ class SimpleClientServerInlineStreamMultiplexerTests: XCTestCase { let reqFrame = HTTP2Frame.FramePayload.headers(.init(headers: headers)) channel.write(reqFrame, promise: nil) - var requestBody = self.clientChannel.allocator.buffer(capacity: 65535) + var requestBody = channel.allocator.buffer(capacity: 65535) requestBody.writeBytes(Array(repeating: UInt8(0x04), count: 65535)) // Now prepare the large body. We need END_STREAM set. diff --git a/Tests/NIOHTTP2Tests/SimpleClientServerTests.swift b/Tests/NIOHTTP2Tests/SimpleClientServerTests.swift index 96c0f8f..ac25d25 100644 --- a/Tests/NIOHTTP2Tests/SimpleClientServerTests.swift +++ b/Tests/NIOHTTP2Tests/SimpleClientServerTests.swift @@ -13,6 +13,7 @@ //===----------------------------------------------------------------------===// import XCTest +import NIOConcurrencyHelpers import NIOCore import NIOEmbedded import NIOHPACK @@ -38,7 +39,7 @@ class SimpleClientServerTests: XCTestCase { @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func basicHTTP2Connection(clientSettings: HTTP2Settings = nioDefaultSettings, serverSettings: HTTP2Settings = nioDefaultSettings, - withMultiplexerCallback multiplexerCallback: ((Channel, HTTP2StreamID) -> EventLoopFuture)? = nil) throws { + withMultiplexerCallback multiplexerCallback: NIOChannelInitializerWithStreamID? = nil) throws { XCTAssertNoThrow(try self.clientChannel.pipeline.addHandler(NIOHTTP2Handler(mode: .client, initialSettings: clientSettings)).wait()) XCTAssertNoThrow(try self.serverChannel.pipeline.addHandler(NIOHTTP2Handler(mode: .server, initialSettings: serverSettings)).wait()) @@ -129,8 +130,9 @@ class SimpleClientServerTests: XCTestCase { // 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")]) - var requestBody = self.clientChannel.allocator.buffer(capacity: 1024) - requestBody.writeBytes(Array(repeating: UInt8(0x04), count: 1024)) + var _requestBody = self.clientChannel.allocator.buffer(capacity: 1024) + _requestBody.writeBytes(Array(repeating: UInt8(0x04), count: 1024)) + let requestBody = _requestBody // We're going to open a stream and queue up the frames for that stream. let handler = try self.clientChannel.pipeline.context(handlerType: HTTP2StreamMultiplexer.self).wait().handler as! HTTP2StreamMultiplexer @@ -229,7 +231,7 @@ class SimpleClientServerTests: XCTestCase { // 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) + var responseBody = channel.allocator.buffer(capacity: 65535) responseBody.writeBytes(Array(repeating: UInt8(0x04), count: 65535)) let respFrame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: responseHeaders))) @@ -247,12 +249,14 @@ class SimpleClientServerTests: XCTestCase { // We're going to open a stream and queue up the frames for that stream. let handler = try self.clientChannel.pipeline.handler(type: HTTP2StreamMultiplexer.self).wait() - var reqFrame: HTTP2Frame? = nil + let reqFrame = NIOLockedValueBox(nil) handler.createStreamChannel(promise: nil) { channel, streamID in // We need END_STREAM set here, because that will force the stream to be closed on the response. - reqFrame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: headers, endStream: true))) - channel.writeAndFlush(reqFrame, promise: nil) + reqFrame.withLockedValue { reqFrame in + reqFrame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: headers, endStream: true))) + channel.writeAndFlush(reqFrame, promise: nil) + } return channel.eventLoop.makeSucceededFuture(()) } self.clientChannel.embeddedEventLoop.run() @@ -264,7 +268,9 @@ class SimpleClientServerTests: XCTestCase { 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.assertFramesMatch([reqFrame!]) + reqFrame.withLockedValue { reqFrame in + childHandler.receivedFrames.assertFramesMatch([reqFrame!]) + } // No other frames should be emitted, though the client may have many in a child stream. self.serverChannel.assertNoFramesReceived() @@ -295,7 +301,7 @@ class SimpleClientServerTests: XCTestCase { let reqFrame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: headers))) channel.write(reqFrame, promise: nil) - var requestBody = self.clientChannel.allocator.buffer(capacity: 65535) + var requestBody = channel.allocator.buffer(capacity: 65535) requestBody.writeBytes(Array(repeating: UInt8(0x04), count: 65535)) // Now prepare the large body. We need END_STREAM set. @@ -438,17 +444,25 @@ class SimpleClientServerTests: XCTestCase { ] ) - XCTAssertEqual(recorder.errors.count, 0) + recorder.errors.withLockedValue { errors in + XCTAssertEqual(errors.count, 0) + } // Send channelInactive followed by channelActive. This can happen if a user calls close // from within a connect promise. channel.pipeline.fireChannelInactive() - XCTAssertEqual(recorder.errors.count, 0) + recorder.errors.withLockedValue { errors in + XCTAssertEqual(errors.count, 0) + } channel.pipeline.fireChannelActive() - XCTAssertEqual(recorder.errors.count, 1) - XCTAssertTrue(recorder.errors.allSatisfy { $0 is NIOHTTP2Errors.ActivationError }) + recorder.errors.withLockedValue { errors in + XCTAssertEqual(errors.count, 1) + } + recorder.errors.withLockedValue { errors in + XCTAssertTrue(errors.allSatisfy { $0 is NIOHTTP2Errors.ActivationError }) + } } func testImpossibleStateTransitionsThrowErrors() throws { @@ -462,7 +476,9 @@ class SimpleClientServerTests: XCTestCase { ] ) - XCTAssertEqual(recorder.errors.count, 0) + recorder.errors.withLockedValue { errors in + XCTAssertEqual(errors.count, 0) + } return (channel, recorder) } @@ -470,8 +486,12 @@ class SimpleClientServerTests: XCTestCase { var (channel, recorder) = try setUpChannel() try channel.pipeline.syncOperations.addHandler(ActionOnFlushHandler { $0.pipeline.fireChannelActive() }, position: .first) channel.pipeline.fireChannelActive() - XCTAssertEqual(recorder.errors.count, 1) - XCTAssertTrue(recorder.errors.allSatisfy { $0 is NIOHTTP2Errors.ActivationError }) + recorder.errors.withLockedValue { errors in + XCTAssertEqual(errors.count, 1) + } + recorder.errors.withLockedValue { errors in + XCTAssertTrue(errors.allSatisfy { $0 is NIOHTTP2Errors.ActivationError }) + } // Second impossible state transition. Synchronous active/inactive/active. The error causes a close, // so we error twice! @@ -484,8 +504,12 @@ class SimpleClientServerTests: XCTestCase { position: .first ) channel.pipeline.fireChannelActive() - XCTAssertEqual(recorder.errors.count, 2) - XCTAssertTrue(recorder.errors.allSatisfy { $0 is NIOHTTP2Errors.ActivationError }) + recorder.errors.withLockedValue { errors in + XCTAssertEqual(errors.count, 2) + } + recorder.errors.withLockedValue { errors in + XCTAssertTrue(errors.allSatisfy { $0 is NIOHTTP2Errors.ActivationError }) + } // Third impossible state transition: active/inactive/active asynchronously. This error doesn't cause a // close because we don't distinguish it from the case tested in @@ -493,10 +517,16 @@ class SimpleClientServerTests: XCTestCase { (channel, recorder) = try setUpChannel() channel.pipeline.fireChannelActive() channel.pipeline.fireChannelInactive() - XCTAssertEqual(recorder.errors.count, 0) + recorder.errors.withLockedValue { errors in + XCTAssertEqual(errors.count, 0) + } channel.pipeline.fireChannelActive() - XCTAssertEqual(recorder.errors.count, 1) - XCTAssertTrue(recorder.errors.allSatisfy { $0 is NIOHTTP2Errors.ActivationError }) + recorder.errors.withLockedValue { errors in + XCTAssertEqual(errors.count, 1) + } + recorder.errors.withLockedValue { errors in + XCTAssertTrue(errors.allSatisfy { $0 is NIOHTTP2Errors.ActivationError }) + } // Fourth impossible state transition: active/inactive/inactive synchronously. The error causes a close, // so we error twice! @@ -509,18 +539,28 @@ class SimpleClientServerTests: XCTestCase { position: .first ) channel.pipeline.fireChannelActive() - XCTAssertEqual(recorder.errors.count, 2) - XCTAssertTrue(recorder.errors.allSatisfy { $0 is NIOHTTP2Errors.ActivationError }) + recorder.errors.withLockedValue { errors in + XCTAssertEqual(errors.count, 2) + } + recorder.errors.withLockedValue { errors in + XCTAssertTrue(errors.allSatisfy { $0 is NIOHTTP2Errors.ActivationError }) + } // Fifth impossible state transition: active/inactive/inactive asynchronously. The error causes a close, // so we error twice! (channel, recorder) = try setUpChannel() channel.pipeline.fireChannelActive() channel.pipeline.fireChannelInactive() - XCTAssertEqual(recorder.errors.count, 0) + recorder.errors.withLockedValue { errors in + XCTAssertEqual(errors.count, 0) + } channel.pipeline.fireChannelInactive() - XCTAssertEqual(recorder.errors.count, 2) - XCTAssertTrue(recorder.errors.allSatisfy { $0 is NIOHTTP2Errors.ActivationError }) + recorder.errors.withLockedValue { errors in + XCTAssertEqual(errors.count, 2) + } + recorder.errors.withLockedValue { errors in + XCTAssertTrue(errors.allSatisfy { $0 is NIOHTTP2Errors.ActivationError }) + } // Sixth impossible state transition: adding the handler twice. The error causes a close, so we // error twice! @@ -528,8 +568,12 @@ class SimpleClientServerTests: XCTestCase { try channel.connect(to: SocketAddress(unixDomainSocketPath: "/tmp/ignored"), promise: nil) let handler = try channel.pipeline.syncOperations.handler(type: NIOHTTP2Handler.self) try channel.pipeline.syncOperations.addHandler(handler, position: .after(handler)) - XCTAssertEqual(recorder.errors.count, 2) - XCTAssertTrue(recorder.errors.allSatisfy { $0 is NIOHTTP2Errors.ActivationError }) + recorder.errors.withLockedValue { errors in + XCTAssertEqual(errors.count, 2) + } + recorder.errors.withLockedValue { errors in + XCTAssertTrue(errors.allSatisfy { $0 is NIOHTTP2Errors.ActivationError }) + } } func testDynamicHeaderFieldsArentEmittedWithZeroTableSize() throws { @@ -577,20 +621,20 @@ class SimpleClientServerTests: XCTestCase { 0x84, // Indexed field, index number 4, static table 0x87, // Indexed field, index number 7, static table 0x41, // Literal field with incremental indexing, index 1, - 0x88, // Huffman-coded value with length 8, - 0x2f, 0x91, 0xd3, - 0x5d, 0x05, 0x5c, - 0x87, 0xa7, + 0x88, // Huffman-coded value with length 8, + 0x2f, 0x91, 0xd3, + 0x5d, 0x05, 0x5c, + 0x87, 0xa7, 0x82, // Indexed field, index number 2, static table 0x40, // Literal field with incremental indexing, new name, - 0x8a, // Huffman-coded name with length 10 - 0x1a, 0xd3, 0x94, - 0x72, 0x16, 0xc5, - 0xa5, 0x31, 0x68, - 0x93, - 0x84, // Huffman-coded value with length 4 - 0x32, 0x14, 0x41, - 0x53 + 0x8a, // Huffman-coded name with length 10 + 0x1a, 0xd3, 0x94, + 0x72, 0x16, 0xc5, + 0xa5, 0x31, 0x68, + 0x93, + 0x84, // Huffman-coded value with length 4 + 0x32, 0x14, 0x41, + 0x53 ]) XCTAssertEqual(expectedBytes, reads.last) diff --git a/Tests/NIOHTTP2Tests/TestUtilities.swift b/Tests/NIOHTTP2Tests/TestUtilities.swift index 561caf3..7bd92b0 100644 --- a/Tests/NIOHTTP2Tests/TestUtilities.swift +++ b/Tests/NIOHTTP2Tests/TestUtilities.swift @@ -88,7 +88,7 @@ extension XCTestCase { } /// Have a `NIOAsyncTestingChannel` send data to another until it makes no forward progress. - func deliverAllBytes(from source: NIOAsyncTestingChannel, to destination: NIOAsyncTestingChannel, file: StaticString = #filePath, line: UInt = #line) async throws { + static func deliverAllBytes(from source: NIOAsyncTestingChannel, to destination: NIOAsyncTestingChannel, file: StaticString = #filePath, line: UInt = #line) async throws { var operated: Bool func readBytesFromChannel(_ channel: NIOAsyncTestingChannel) async -> ByteBuffer? { diff --git a/docker/docker-compose.2204.510.yaml b/docker/docker-compose.2204.510.yaml index b10e955..5682b2e 100644 --- a/docker/docker-compose.2204.510.yaml +++ b/docker/docker-compose.2204.510.yaml @@ -31,11 +31,11 @@ services: - MAX_ALLOCS_ALLOWED_1k_requests_inline_noninterleaved=34100 - MAX_ALLOCS_ALLOWED_1k_requests_interleaved=41150 - MAX_ALLOCS_ALLOWED_1k_requests_noninterleaved=40100 - - MAX_ALLOCS_ALLOWED_client_server_h1_request_response=296050 + - MAX_ALLOCS_ALLOWED_client_server_h1_request_response=288050 - MAX_ALLOCS_ALLOWED_client_server_h1_request_response_inline=273050 - - MAX_ALLOCS_ALLOWED_client_server_request_response=265050 + - MAX_ALLOCS_ALLOWED_client_server_request_response=257050 - MAX_ALLOCS_ALLOWED_client_server_request_response_inline=248050 - - MAX_ALLOCS_ALLOWED_client_server_request_response_many=1210050 + - MAX_ALLOCS_ALLOWED_client_server_request_response_many=1202050 - MAX_ALLOCS_ALLOWED_client_server_request_response_many_inline=893050 - MAX_ALLOCS_ALLOWED_create_client_stream_channel=39050 - MAX_ALLOCS_ALLOWED_create_client_stream_channel_inline=39050 @@ -44,7 +44,7 @@ services: - 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=293050 + - MAX_ALLOCS_ALLOWED_stream_teardown_100_concurrent=292650 - MAX_ALLOCS_ALLOWED_stream_teardown_100_concurrent_inline=291750 - IMPORT_CHECK_ARG=--explicit-target-dependency-import-check error diff --git a/docker/docker-compose.2204.57.yaml b/docker/docker-compose.2204.57.yaml index 0a0bcec..5566ba2 100644 --- a/docker/docker-compose.2204.57.yaml +++ b/docker/docker-compose.2204.57.yaml @@ -32,11 +32,11 @@ services: - MAX_ALLOCS_ALLOWED_1k_requests_inline_noninterleaved=34100 - MAX_ALLOCS_ALLOWED_1k_requests_interleaved=41150 - MAX_ALLOCS_ALLOWED_1k_requests_noninterleaved=40100 - - MAX_ALLOCS_ALLOWED_client_server_h1_request_response=296050 + - MAX_ALLOCS_ALLOWED_client_server_h1_request_response=288050 - MAX_ALLOCS_ALLOWED_client_server_h1_request_response_inline=273050 - - MAX_ALLOCS_ALLOWED_client_server_request_response=265050 + - MAX_ALLOCS_ALLOWED_client_server_request_response=257050 - MAX_ALLOCS_ALLOWED_client_server_request_response_inline=248050 - - MAX_ALLOCS_ALLOWED_client_server_request_response_many=1210050 + - MAX_ALLOCS_ALLOWED_client_server_request_response_many=1202050 - MAX_ALLOCS_ALLOWED_client_server_request_response_many_inline=893050 - MAX_ALLOCS_ALLOWED_create_client_stream_channel=39050 - MAX_ALLOCS_ALLOWED_create_client_stream_channel_inline=39050 @@ -45,7 +45,7 @@ services: - 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=293050 + - MAX_ALLOCS_ALLOWED_stream_teardown_100_concurrent=292650 - MAX_ALLOCS_ALLOWED_stream_teardown_100_concurrent_inline=291750 shell: diff --git a/docker/docker-compose.2204.58.yaml b/docker/docker-compose.2204.58.yaml index bb18506..30b667c 100644 --- a/docker/docker-compose.2204.58.yaml +++ b/docker/docker-compose.2204.58.yaml @@ -32,11 +32,11 @@ services: - MAX_ALLOCS_ALLOWED_1k_requests_inline_noninterleaved=34100 - MAX_ALLOCS_ALLOWED_1k_requests_interleaved=41150 - MAX_ALLOCS_ALLOWED_1k_requests_noninterleaved=40100 - - MAX_ALLOCS_ALLOWED_client_server_h1_request_response=296050 + - MAX_ALLOCS_ALLOWED_client_server_h1_request_response=288050 - MAX_ALLOCS_ALLOWED_client_server_h1_request_response_inline=273050 - - MAX_ALLOCS_ALLOWED_client_server_request_response=265050 + - MAX_ALLOCS_ALLOWED_client_server_request_response=257050 - MAX_ALLOCS_ALLOWED_client_server_request_response_inline=248050 - - MAX_ALLOCS_ALLOWED_client_server_request_response_many=1210050 + - MAX_ALLOCS_ALLOWED_client_server_request_response_many=1202050 - MAX_ALLOCS_ALLOWED_client_server_request_response_many_inline=893050 - MAX_ALLOCS_ALLOWED_create_client_stream_channel=39050 - MAX_ALLOCS_ALLOWED_create_client_stream_channel_inline=39050 @@ -45,7 +45,7 @@ services: - 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=293050 + - MAX_ALLOCS_ALLOWED_stream_teardown_100_concurrent=292650 - MAX_ALLOCS_ALLOWED_stream_teardown_100_concurrent_inline=291750 - IMPORT_CHECK_ARG=--explicit-target-dependency-import-check error diff --git a/docker/docker-compose.2204.59.yaml b/docker/docker-compose.2204.59.yaml index cac5c27..bd23558 100644 --- a/docker/docker-compose.2204.59.yaml +++ b/docker/docker-compose.2204.59.yaml @@ -32,11 +32,11 @@ services: - MAX_ALLOCS_ALLOWED_1k_requests_inline_noninterleaved=34100 - MAX_ALLOCS_ALLOWED_1k_requests_interleaved=41150 - MAX_ALLOCS_ALLOWED_1k_requests_noninterleaved=40100 - - MAX_ALLOCS_ALLOWED_client_server_h1_request_response=296050 + - MAX_ALLOCS_ALLOWED_client_server_h1_request_response=288050 - MAX_ALLOCS_ALLOWED_client_server_h1_request_response_inline=273050 - - MAX_ALLOCS_ALLOWED_client_server_request_response=265050 + - MAX_ALLOCS_ALLOWED_client_server_request_response=257050 - MAX_ALLOCS_ALLOWED_client_server_request_response_inline=248050 - - MAX_ALLOCS_ALLOWED_client_server_request_response_many=1210050 + - MAX_ALLOCS_ALLOWED_client_server_request_response_many=1202050 - MAX_ALLOCS_ALLOWED_client_server_request_response_many_inline=893050 - MAX_ALLOCS_ALLOWED_create_client_stream_channel=39050 - MAX_ALLOCS_ALLOWED_create_client_stream_channel_inline=39050 @@ -45,7 +45,7 @@ services: - 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=293050 + - MAX_ALLOCS_ALLOWED_stream_teardown_100_concurrent=292650 - MAX_ALLOCS_ALLOWED_stream_teardown_100_concurrent_inline=291750 - IMPORT_CHECK_ARG=--explicit-target-dependency-import-check error diff --git a/docker/docker-compose.2204.main.yaml b/docker/docker-compose.2204.main.yaml index 6313706..174c975 100644 --- a/docker/docker-compose.2204.main.yaml +++ b/docker/docker-compose.2204.main.yaml @@ -31,11 +31,11 @@ services: - MAX_ALLOCS_ALLOWED_1k_requests_inline_noninterleaved=34100 - MAX_ALLOCS_ALLOWED_1k_requests_interleaved=41150 - MAX_ALLOCS_ALLOWED_1k_requests_noninterleaved=40100 - - MAX_ALLOCS_ALLOWED_client_server_h1_request_response=296050 + - MAX_ALLOCS_ALLOWED_client_server_h1_request_response=288050 - MAX_ALLOCS_ALLOWED_client_server_h1_request_response_inline=273050 - - MAX_ALLOCS_ALLOWED_client_server_request_response=265050 + - MAX_ALLOCS_ALLOWED_client_server_request_response=257050 - MAX_ALLOCS_ALLOWED_client_server_request_response_inline=248050 - - MAX_ALLOCS_ALLOWED_client_server_request_response_many=1210050 + - MAX_ALLOCS_ALLOWED_client_server_request_response_many=1202050 - MAX_ALLOCS_ALLOWED_client_server_request_response_many_inline=893050 - MAX_ALLOCS_ALLOWED_create_client_stream_channel=39050 - MAX_ALLOCS_ALLOWED_create_client_stream_channel_inline=39050 @@ -44,7 +44,7 @@ services: - 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=293050 + - MAX_ALLOCS_ALLOWED_stream_teardown_100_concurrent=292650 - MAX_ALLOCS_ALLOWED_stream_teardown_100_concurrent_inline=291750 - IMPORT_CHECK_ARG=--explicit-target-dependency-import-check error