From 2f58d8ef84438d6517fc78bcea2f8527e3c72936 Mon Sep 17 00:00:00 2001 From: Aryan Shah Date: Mon, 2 Nov 2026 13:00:48 +0000 Subject: [PATCH] Revert configuration type for HTTP/1 server pipeline setup (#3775) ### Motivation: We introduced a new configuration type in #3746 to make further extensions to the server pipeline (#3745 for example) easier to introduce. The plan was to merge #3745 soon after #3746 was merged, because #3745 added a breaking change to the new config type. However, #3745 needs some more consideration. We should therefore revert the change in #3746 to unblock new releases from being made until we come up with a better solution. ### Modifications: A clean revert of PR #3746. ### Result: Unblocks new releases. --- .../test_01_resources/shared.swift | 8 +- .../SingleStepByteToMessageDecoder.swift | 2 +- Sources/NIOHTTP1/HTTPPipelineSetup.swift | 416 ++++++------------ Sources/NIOHTTP1Server/main.swift | 2 +- Sources/NIOPerformanceTester/main.swift | 7 +- .../HTTPHeaderValidationTests.swift | 40 +- .../HTTPResponseEncoderTest.swift | 22 +- .../NIOHTTP1Tests/HTTPServerClientTest.swift | 67 ++- .../HTTPServerPipelineSetupTests.swift | 276 ------------ .../HTTPServerProtocolErrorHandlerTest.swift | 42 +- .../HTTPServerUpgradeTests.swift | 66 +-- .../WebSocketServerEndToEndTests.swift | 12 +- 12 files changed, 257 insertions(+), 703 deletions(-) delete mode 100644 Tests/NIOHTTP1Tests/HTTPServerPipelineSetupTests.swift diff --git a/IntegrationTests/tests_04_performance/test_01_resources/shared.swift b/IntegrationTests/tests_04_performance/test_01_resources/shared.swift index 59107f734..6677fdc01 100644 --- a/IntegrationTests/tests_04_performance/test_01_resources/shared.swift +++ b/IntegrationTests/tests_04_performance/test_01_resources/shared.swift @@ -111,10 +111,10 @@ func doRequests(group: EventLoopGroup, number numberOfRequests: Int) throws -> I let serverChannel = try ServerBootstrap(group: group) .serverChannelOption(.socketOption(.so_reuseaddr), value: 1) .childChannelInitializer { channel in - var configuration = NIOHTTPServerPipelineConfiguration() - configuration.pipeliningAssistance = true - configuration.errorHandling = false - return channel.pipeline.configureHTTPServerPipeline(configuration: configuration).flatMap { + channel.pipeline.configureHTTPServerPipeline( + withPipeliningAssistance: true, + withErrorHandling: false + ).flatMap { channel.pipeline.addHandler(SimpleHTTPServer()) } }.bind(to: localhostPickPort).wait() diff --git a/Sources/NIOCore/SingleStepByteToMessageDecoder.swift b/Sources/NIOCore/SingleStepByteToMessageDecoder.swift index c604b1e4c..0855a73ec 100644 --- a/Sources/NIOCore/SingleStepByteToMessageDecoder.swift +++ b/Sources/NIOCore/SingleStepByteToMessageDecoder.swift @@ -182,7 +182,7 @@ extension NIOSingleStepByteToMessageDecoder where Self: ~Copyable { /// /// let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) /// let bootstrap = ServerBootstrap(group: group).childChannelInitializer({channel in -/// channel.pipeline.configureHTTPServerPipeline().flatMap { _ in +/// channel.pipeline.configureHTTPServerPipeline(withPipeliningAssistance: true, withErrorHandling: true).flatMap { _ in /// channel.pipeline.addHandlers([RawBodyMessageHandler(), DecodedBodyHTTPHandler()]) /// } /// }) diff --git a/Sources/NIOHTTP1/HTTPPipelineSetup.swift b/Sources/NIOHTTP1/HTTPPipelineSetup.swift index 2c4dfd809..dc1d613eb 100644 --- a/Sources/NIOHTTP1/HTTPPipelineSetup.swift +++ b/Sources/NIOHTTP1/HTTPPipelineSetup.swift @@ -229,20 +229,18 @@ extension ChannelPipeline { /// failure to parse the HTTP request) by sending 400 errors. Defaults to `true`. /// - Returns: An `EventLoopFuture` that will fire when the pipeline is configured. @preconcurrency - @available(*, deprecated, message: "Use configureHTTPServerPipeline(position:configuration:) instead") - @_disfavoredOverload public func configureHTTPServerPipeline( position: ChannelPipeline.Position = .last, withPipeliningAssistance pipelining: Bool = true, withServerUpgrade upgrade: NIOHTTPServerUpgradeSendableConfiguration? = nil, withErrorHandling errorHandling: Bool = true ) -> EventLoopFuture { - var configuration = NIOHTTPServerPipelineConfiguration() - configuration.pipeliningAssistance = pipelining - configuration.serverUpgrade = upgrade.map { NIOHTTPServerPipelineConfiguration.UpgradeConfiguration($0) } - configuration.errorHandling = errorHandling - - return self.configureHTTPServerPipeline(position: position, configuration: configuration) + self._configureHTTPServerPipeline( + position: position, + withPipeliningAssistance: pipelining, + withServerUpgrade: upgrade, + withErrorHandling: errorHandling + ) } /// Configure a `ChannelPipeline` for use as a HTTP server. @@ -275,8 +273,6 @@ extension ChannelPipeline { /// spec compliance. Defaults to `true`. /// - Returns: An `EventLoopFuture` that will fire when the pipeline is configured. @preconcurrency - @available(*, deprecated, message: "Use configureHTTPServerPipeline(position:configuration:) instead") - @_disfavoredOverload public func configureHTTPServerPipeline( position: ChannelPipeline.Position = .last, withPipeliningAssistance pipelining: Bool = true, @@ -284,13 +280,13 @@ extension ChannelPipeline { withErrorHandling errorHandling: Bool = true, withOutboundHeaderValidation headerValidation: Bool = true ) -> EventLoopFuture { - var configuration = NIOHTTPServerPipelineConfiguration() - configuration.pipeliningAssistance = pipelining - configuration.serverUpgrade = upgrade.map { NIOHTTPServerPipelineConfiguration.UpgradeConfiguration($0) } - configuration.errorHandling = errorHandling - configuration.outboundHeaderValidation = headerValidation - - return self.configureHTTPServerPipeline(position: position, configuration: configuration) + self._configureHTTPServerPipeline( + position: position, + withPipeliningAssistance: pipelining, + withServerUpgrade: upgrade, + withErrorHandling: errorHandling, + withOutboundHeaderValidation: headerValidation + ) } /// Configure a `ChannelPipeline` for use as a HTTP server. @@ -324,8 +320,6 @@ extension ChannelPipeline { /// - encoderConfiguration: The configuration for the ``HTTPResponseEncoder``. /// - Returns: An `EventLoopFuture` that will fire when the pipeline is configured. @preconcurrency - @available(*, deprecated, message: "Use configureHTTPServerPipeline(position:configuration:) instead") - @_disfavoredOverload public func configureHTTPServerPipeline( position: ChannelPipeline.Position = .last, withPipeliningAssistance pipelining: Bool = true, @@ -334,14 +328,14 @@ extension ChannelPipeline { withOutboundHeaderValidation headerValidation: Bool = true, withEncoderConfiguration encoderConfiguration: HTTPResponseEncoder.Configuration = .init() ) -> EventLoopFuture { - var configuration = NIOHTTPServerPipelineConfiguration() - configuration.pipeliningAssistance = pipelining - configuration.serverUpgrade = upgrade.map { NIOHTTPServerPipelineConfiguration.UpgradeConfiguration($0) } - configuration.errorHandling = errorHandling - configuration.outboundHeaderValidation = headerValidation - configuration.encoderConfiguration = encoderConfiguration - - return self.configureHTTPServerPipeline(position: position, configuration: configuration) + self._configureHTTPServerPipeline( + position: position, + withPipeliningAssistance: pipelining, + withServerUpgrade: upgrade, + withErrorHandling: errorHandling, + withOutboundHeaderValidation: headerValidation, + withEncoderConfiguration: encoderConfiguration + ) } /// Configure a `ChannelPipeline` for use as a HTTP server. @@ -376,8 +370,6 @@ extension ChannelPipeline { /// - decoderLimitConfiguration: The limit configuration for the ``HTTPDecoder``. /// - Returns: An `EventLoopFuture` that will fire when the pipeline is configured. @preconcurrency - @available(*, deprecated, message: "Use configureHTTPServerPipeline(position:configuration:) instead") - @_disfavoredOverload public func configureHTTPServerPipeline( position: ChannelPipeline.Position = .last, withPipeliningAssistance pipelining: Bool = true, @@ -387,51 +379,58 @@ extension ChannelPipeline { withEncoderConfiguration encoderConfiguration: HTTPResponseEncoder.Configuration = .init(), withDecoderLimitConfiguration decoderLimitConfiguration: NIOHTTPDecoderLimitConfiguration = .init() ) -> EventLoopFuture { - var configuration = NIOHTTPServerPipelineConfiguration() - configuration.pipeliningAssistance = pipelining - configuration.serverUpgrade = upgrade.map { NIOHTTPServerPipelineConfiguration.UpgradeConfiguration($0) } - configuration.errorHandling = errorHandling - configuration.outboundHeaderValidation = headerValidation - configuration.encoderConfiguration = encoderConfiguration - configuration.decoderLimitConfiguration = decoderLimitConfiguration - - return self.configureHTTPServerPipeline(position: position, configuration: configuration) + self._configureHTTPServerPipeline( + position: position, + withPipeliningAssistance: pipelining, + withServerUpgrade: upgrade, + withErrorHandling: errorHandling, + withOutboundHeaderValidation: headerValidation, + withEncoderConfiguration: encoderConfiguration, + withDecoderLimitConfiguration: decoderLimitConfiguration + ) } - /// Configure a `ChannelPipeline` for use as a HTTP server. - /// - /// This function knows how to set up all first-party HTTP channel handlers appropriately for server use. It - /// supports the following features, depending on the provided `configuration`: - /// - /// 1. Providing assistance handling clients that pipeline HTTP requests, using the ``HTTPServerPipelineHandler``. - /// 2. Supporting HTTP upgrade, using the ``HTTPServerUpgradeHandler``. - /// 3. Providing assistance handling protocol errors. - /// 4. Validating outbound header fields to protect against response splitting attacks. - /// - /// - Parameters: - /// - position: Where in the pipeline to add the HTTP server handlers. Defaults to `.last`. - /// - configuration: The configuration for the HTTP server pipeline. Defaults to - /// ``NIOHTTPServerPipelineConfiguration/init()``. - /// - Returns: An `EventLoopFuture` that will fire when the pipeline is configured. - public func configureHTTPServerPipeline( + private func _configureHTTPServerPipeline( position: ChannelPipeline.Position = .last, - configuration: NIOHTTPServerPipelineConfiguration = .init() + withPipeliningAssistance pipelining: Bool = true, + withServerUpgrade upgrade: NIOHTTPServerUpgradeSendableConfiguration? = nil, + withErrorHandling errorHandling: Bool = true, + withOutboundHeaderValidation headerValidation: Bool = true, + withEncoderConfiguration encoderConfiguration: HTTPResponseEncoder.Configuration = .init(), + withDecoderLimitConfiguration decoderLimitConfiguration: NIOHTTPDecoderLimitConfiguration = .init() ) -> EventLoopFuture { + let future: EventLoopFuture + if self.eventLoop.inEventLoop { - return self.eventLoop.makeCompletedFuture { + let syncPosition = ChannelPipeline.SynchronousOperations.Position(position) + let result = Result { try self.syncOperations.configureHTTPServerPipeline( - position: .init(position), - configuration: .init(configuration) + position: syncPosition, + withPipeliningAssistance: pipelining, + withServerUpgrade: upgrade, + withErrorHandling: errorHandling, + withOutboundHeaderValidation: headerValidation, + withEncoderConfiguration: encoderConfiguration, + withDecoderLimitConfiguration: decoderLimitConfiguration + ) + } + future = self.eventLoop.makeCompletedFuture(result) + } else { + future = self.eventLoop.submit { + let syncPosition = ChannelPipeline.SynchronousOperations.Position(position) + try self.syncOperations.configureHTTPServerPipeline( + position: syncPosition, + withPipeliningAssistance: pipelining, + withServerUpgrade: upgrade, + withErrorHandling: errorHandling, + withOutboundHeaderValidation: headerValidation, + withEncoderConfiguration: encoderConfiguration, + withDecoderLimitConfiguration: decoderLimitConfiguration ) } } - return self.eventLoop.submit { - try self.syncOperations.configureHTTPServerPipeline( - position: .init(position), - configuration: .init(configuration) - ) - } + return future } } @@ -747,19 +746,18 @@ extension ChannelPipeline.SynchronousOperations { /// - errorHandling: Whether to provide assistance handling protocol errors (e.g. /// failure to parse the HTTP request) by sending 400 errors. Defaults to `true`. /// - Throws: If the pipeline could not be configured. - @available(*, deprecated, message: "Use configureHTTPServerPipeline(position:configuration:) instead") public func configureHTTPServerPipeline( position: ChannelPipeline.SynchronousOperations.Position = .last, withPipeliningAssistance pipelining: Bool = true, withServerUpgrade upgrade: NIOHTTPServerUpgradeConfiguration? = nil, withErrorHandling errorHandling: Bool = true ) throws { - var configuration = NIOHTTPServerPipelineSynchronousConfiguration() - configuration.pipeliningAssistance = pipelining - configuration.serverUpgrade = upgrade.map { .init($0) } - configuration.errorHandling = errorHandling - - try self.configureHTTPServerPipeline(position: position, configuration: configuration) + try self._configureHTTPServerPipeline( + position: position, + withPipeliningAssistance: pipelining, + withServerUpgrade: upgrade, + withErrorHandling: errorHandling + ) } /// Configure a `ChannelPipeline` for use as a HTTP server. @@ -789,7 +787,7 @@ extension ChannelPipeline.SynchronousOperations { /// failure to parse the HTTP request) by sending 400 errors. Defaults to `true`. /// - Throws: If the pipeline could not be configured. @preconcurrency - @available(*, deprecated, message: "Use configureHTTPServerPipeline(position:configuration:) instead") + @available(*, deprecated, message: "Use ChannelPipeline.SynchronousOperations.Position instead") @_disfavoredOverload public func configureHTTPServerPipeline( position: ChannelPipeline.Position = .last, @@ -798,12 +796,12 @@ extension ChannelPipeline.SynchronousOperations { withErrorHandling errorHandling: Bool = true ) throws { let syncPosition = ChannelPipeline.SynchronousOperations.Position(position) - var configuration = NIOHTTPServerPipelineSynchronousConfiguration() - configuration.pipeliningAssistance = pipelining - configuration.serverUpgrade = upgrade.map { .init($0) } - configuration.errorHandling = errorHandling - - try self.configureHTTPServerPipeline(position: syncPosition, configuration: configuration) + try self._configureHTTPServerPipeline( + position: syncPosition, + withPipeliningAssistance: pipelining, + withServerUpgrade: upgrade, + withErrorHandling: errorHandling + ) } /// Configure a `ChannelPipeline` for use as a HTTP server. @@ -836,7 +834,6 @@ extension ChannelPipeline.SynchronousOperations { /// - headerValidation: Whether to validate outbound request headers to confirm that they meet /// spec compliance. Defaults to `true`. /// - Throws: If the pipeline could not be configured. - @available(*, deprecated, message: "Use configureHTTPServerPipeline(position:configuration:) instead") public func configureHTTPServerPipeline( position: ChannelPipeline.SynchronousOperations.Position = .last, withPipeliningAssistance pipelining: Bool = true, @@ -844,13 +841,13 @@ extension ChannelPipeline.SynchronousOperations { withErrorHandling errorHandling: Bool = true, withOutboundHeaderValidation headerValidation: Bool = true ) throws { - var configuration = NIOHTTPServerPipelineSynchronousConfiguration() - configuration.pipeliningAssistance = pipelining - configuration.serverUpgrade = upgrade.map { .init($0) } - configuration.errorHandling = errorHandling - configuration.outboundHeaderValidation = headerValidation - - try self.configureHTTPServerPipeline(position: position, configuration: configuration) + try self._configureHTTPServerPipeline( + position: position, + withPipeliningAssistance: pipelining, + withServerUpgrade: upgrade, + withErrorHandling: errorHandling, + withOutboundHeaderValidation: headerValidation + ) } /// Configure a `ChannelPipeline` for use as a HTTP server. @@ -883,7 +880,7 @@ extension ChannelPipeline.SynchronousOperations { /// - headerValidation: Whether to validate outbound request headers to confirm that they meet /// spec compliance. Defaults to `true`. /// - Throws: If the pipeline could not be configured. - @available(*, deprecated, message: "Use configureHTTPServerPipeline(position:configuration:) instead") + @available(*, deprecated, message: "Use ChannelPipeline.SynchronousOperations.Position instead") @_disfavoredOverload public func configureHTTPServerPipeline( position: ChannelPipeline.Position = .last, @@ -893,13 +890,13 @@ extension ChannelPipeline.SynchronousOperations { withOutboundHeaderValidation headerValidation: Bool = true ) throws { let syncPosition = ChannelPipeline.SynchronousOperations.Position(position) - var configuration = NIOHTTPServerPipelineSynchronousConfiguration() - configuration.pipeliningAssistance = pipelining - configuration.serverUpgrade = upgrade.map { .init($0) } - configuration.errorHandling = errorHandling - configuration.outboundHeaderValidation = headerValidation - - try self.configureHTTPServerPipeline(position: syncPosition, configuration: configuration) + try self._configureHTTPServerPipeline( + position: syncPosition, + withPipeliningAssistance: pipelining, + withServerUpgrade: upgrade, + withErrorHandling: errorHandling, + withOutboundHeaderValidation: headerValidation + ) } /// Configure a `ChannelPipeline` for use as a HTTP server. @@ -933,7 +930,6 @@ extension ChannelPipeline.SynchronousOperations { /// spec compliance. Defaults to `true`. /// - encoderConfiguration: The configuration for the ``HTTPRequestEncoder``. /// - Throws: If the pipeline could not be configured. - @available(*, deprecated, message: "Use configureHTTPServerPipeline(position:configuration:) instead") public func configureHTTPServerPipeline( position: ChannelPipeline.SynchronousOperations.Position = .last, withPipeliningAssistance pipelining: Bool = true, @@ -942,14 +938,14 @@ extension ChannelPipeline.SynchronousOperations { withOutboundHeaderValidation headerValidation: Bool = true, withEncoderConfiguration encoderConfiguration: HTTPResponseEncoder.Configuration ) throws { - var configuration = NIOHTTPServerPipelineSynchronousConfiguration() - configuration.pipeliningAssistance = pipelining - configuration.serverUpgrade = upgrade.map { .init($0) } - configuration.errorHandling = errorHandling - configuration.outboundHeaderValidation = headerValidation - configuration.encoderConfiguration = encoderConfiguration - - try self.configureHTTPServerPipeline(position: position, configuration: configuration) + try self._configureHTTPServerPipeline( + position: position, + withPipeliningAssistance: pipelining, + withServerUpgrade: upgrade, + withErrorHandling: errorHandling, + withOutboundHeaderValidation: headerValidation, + withEncoderConfiguration: encoderConfiguration + ) } /// Configure a `ChannelPipeline` for use as a HTTP server. @@ -984,7 +980,6 @@ extension ChannelPipeline.SynchronousOperations { /// - encoderConfiguration: The configuration for the ``HTTPRequestEncoder``. /// - decoderLimitConfiguration: The limit configuration for the ``HTTPDecoder``. /// - Throws: If the pipeline could not be configured. - @available(*, deprecated, message: "Use configureHTTPServerPipeline(position:configuration:) instead") public func configureHTTPServerPipeline( position: ChannelPipeline.SynchronousOperations.Position = .last, withPipeliningAssistance pipelining: Bool = true, @@ -994,15 +989,15 @@ extension ChannelPipeline.SynchronousOperations { withEncoderConfiguration encoderConfiguration: HTTPResponseEncoder.Configuration, withDecoderLimitConfiguration decoderLimitConfiguration: NIOHTTPDecoderLimitConfiguration, ) throws { - var configuration = NIOHTTPServerPipelineSynchronousConfiguration() - configuration.pipeliningAssistance = pipelining - configuration.serverUpgrade = upgrade.map { .init($0) } - configuration.errorHandling = errorHandling - configuration.outboundHeaderValidation = headerValidation - configuration.encoderConfiguration = encoderConfiguration - configuration.decoderLimitConfiguration = decoderLimitConfiguration - - try self.configureHTTPServerPipeline(position: position, configuration: configuration) + try self._configureHTTPServerPipeline( + position: position, + withPipeliningAssistance: pipelining, + withServerUpgrade: upgrade, + withErrorHandling: errorHandling, + withOutboundHeaderValidation: headerValidation, + withEncoderConfiguration: encoderConfiguration, + withDecoderLimitConfiguration: decoderLimitConfiguration + ) } /// Configure a `ChannelPipeline` for use as a HTTP server. @@ -1036,7 +1031,7 @@ extension ChannelPipeline.SynchronousOperations { /// spec compliance. Defaults to `true`. /// - encoderConfiguration: The configuration for the ``HTTPRequestEncoder``. /// - Throws: If the pipeline could not be configured. - @available(*, deprecated, message: "Use configureHTTPServerPipeline(position:configuration:) instead") + @available(*, deprecated, message: "Use ChannelPipeline.SynchronousOperations.Position instead") @_disfavoredOverload public func configureHTTPServerPipeline( position: ChannelPipeline.Position = .last, @@ -1047,68 +1042,56 @@ extension ChannelPipeline.SynchronousOperations { withEncoderConfiguration encoderConfiguration: HTTPResponseEncoder.Configuration ) throws { let syncPosition = ChannelPipeline.SynchronousOperations.Position(position) - var configuration = NIOHTTPServerPipelineSynchronousConfiguration() - configuration.pipeliningAssistance = pipelining - configuration.serverUpgrade = upgrade.map { .init($0) } - configuration.errorHandling = errorHandling - configuration.outboundHeaderValidation = headerValidation - configuration.encoderConfiguration = encoderConfiguration - - try self.configureHTTPServerPipeline(position: syncPosition, configuration: configuration) + try self._configureHTTPServerPipeline( + position: syncPosition, + withPipeliningAssistance: pipelining, + withServerUpgrade: upgrade, + withErrorHandling: errorHandling, + withOutboundHeaderValidation: headerValidation, + withEncoderConfiguration: encoderConfiguration + ) } - /// Configure a `ChannelPipeline` for use as a HTTP server. - /// - /// This function knows how to set up all first-party HTTP channel handlers appropriately for server use. It - /// supports the following features, depending on the provided `configuration`: - /// - /// 1. Providing assistance handling clients that pipeline HTTP requests, using the `HTTPServerPipelineHandler`. - /// 2. Supporting HTTP upgrade, using the `HTTPServerUpgradeHandler`. - /// 3. Providing assistance handling protocol errors. - /// 4. Validating outbound header fields to protect against response splitting attacks. - /// - /// - Important: This **must** be called on the Channel's event loop. - /// - /// - Parameters: - /// - position: Where in the pipeline to add the HTTP server handlers. Defaults to `.last`. - /// - configuration: The configuration for the HTTP server pipeline. Defaults to - /// ``NIOHTTPServerPipelineSynchronousConfiguration/init()``. - /// - Throws: If the pipeline could not be configured. - public func configureHTTPServerPipeline( + private func _configureHTTPServerPipeline( position: ChannelPipeline.SynchronousOperations.Position = .last, - configuration: NIOHTTPServerPipelineSynchronousConfiguration = .init() + withPipeliningAssistance pipelining: Bool = true, + withServerUpgrade upgrade: NIOHTTPServerUpgradeConfiguration? = nil, + withErrorHandling errorHandling: Bool = true, + withOutboundHeaderValidation headerValidation: Bool = true, + withEncoderConfiguration encoderConfiguration: HTTPResponseEncoder.Configuration = .init(), + withDecoderLimitConfiguration decoderLimitConfiguration: NIOHTTPDecoderLimitConfiguration = .init() ) throws { self.eventLoop.assertInEventLoop() - let responseEncoder = HTTPResponseEncoder(configuration: configuration.encoderConfiguration) + let responseEncoder = HTTPResponseEncoder(configuration: encoderConfiguration) // The encoder is outbound-only; the request decoder feeds it each decoded request's method // so responses to HEAD/CONNECT are encoded without a body. let requestDecoder = HTTPRequestDecoder( - leftOverBytesStrategy: configuration.serverUpgrade == nil ? .dropBytes : .forwardBytes, - limitConfiguration: configuration.decoderLimitConfiguration, + leftOverBytesStrategy: upgrade == nil ? .dropBytes : .forwardBytes, + limitConfiguration: decoderLimitConfiguration, responseEncoder: responseEncoder ) var handlers: [RemovableChannelHandler] = [responseEncoder, ByteToMessageHandler(requestDecoder)] - if configuration.pipeliningAssistance { + if pipelining { handlers.append(HTTPServerPipelineHandler()) } - if configuration.outboundHeaderValidation { + if headerValidation { handlers.append(NIOHTTPResponseHeadersValidator()) } - if configuration.errorHandling { + if errorHandling { handlers.append(HTTPServerProtocolErrorHandler()) } - if let upgrade = configuration.serverUpgrade { + if let (upgraders, completionHandler) = upgrade { let upgrader = HTTPServerUpgradeHandler( - upgraders: upgrade.upgraders, + upgraders: upgraders, httpEncoder: responseEncoder, extraHTTPHandlers: Array(handlers.dropFirst()), - upgradeCompletionHandler: upgrade.completionHandler + upgradeCompletionHandler: completionHandler ) handlers.append(upgrader) } @@ -1116,136 +1099,3 @@ extension ChannelPipeline.SynchronousOperations { try self.addHandlers(handlers, position: position) } } - -/// The configuration for a HTTP server pipeline. -/// -/// The upgraders in this configuration must be `Sendable`. If you are configuring the pipeline synchronously on the -/// Channel's event loop and your upgraders are not `Sendable`, use ``NIOHTTPServerPipelineSynchronousConfiguration`` -/// with ``NIOCore/ChannelPipeline/SynchronousOperations/configureHTTPServerPipeline(position:configuration:)`` instead. -public struct NIOHTTPServerPipelineConfiguration: Sendable { - /// Whether to provide assistance handling HTTP clients that pipeline their requests. Defaults to `true`. If - /// `false`, users will need to handle clients that pipeline themselves. - public var pipeliningAssistance: Bool = true - - /// Whether to add a ``HTTPServerUpgradeHandler`` to the pipeline, configured for HTTP upgrade. Defaults to `nil`, - /// which will not add the handler to the pipeline. See the documentation on ``HTTPServerUpgradeHandler`` for more - /// details. - public var serverUpgrade: UpgradeConfiguration? = nil - - /// Whether to provide assistance handling protocol errors (e.g. failure to parse the HTTP request) by sending - /// 400 errors. Defaults to `true`. - public var errorHandling: Bool = true - - /// Whether to validate outbound response headers to confirm that they meet spec compliance. Defaults to `true`. - public var outboundHeaderValidation: Bool = true - - /// The configuration for the ``HTTPResponseEncoder``. Defaults to ``HTTPResponseEncoder/Configuration/init()``. - public var encoderConfiguration: HTTPResponseEncoder.Configuration = .init() - - /// The limit configuration for the ``HTTPDecoder``. Defaults to ``NIOHTTPDecoderLimitConfiguration/init()``. - public var decoderLimitConfiguration: NIOHTTPDecoderLimitConfiguration = .init() - - /// The configuration for HTTP upgrade. - public struct UpgradeConfiguration: Sendable { - /// The upgraders the server supports, in order of preference. - public var upgraders: [HTTPServerProtocolUpgrader & Sendable] - - /// Called once the upgrade is complete, with the context of the handler performing the upgrade. - public var completionHandler: @Sendable (ChannelHandlerContext) -> Void - - /// Creates an upgrade configuration. - /// - /// - Parameters: - /// - upgraders: The upgraders the server supports, in order of preference. - /// - completionHandler: Called once the upgrade is complete, with the context of the handler performing - /// the upgrade. - public init( - upgraders: [HTTPServerProtocolUpgrader & Sendable], - completionHandler: @escaping @Sendable (ChannelHandlerContext) -> Void - ) { - self.upgraders = upgraders - self.completionHandler = completionHandler - } - - fileprivate init(_ configuration: NIOHTTPServerUpgradeSendableConfiguration) { - self.init(upgraders: configuration.upgraders, completionHandler: configuration.completionHandler) - } - } - - /// Creates a configuration with the default values. - public init() {} -} - -/// The configuration for a HTTP server pipeline set up synchronously on the Channel's event loop. -/// -/// This is identical to ``NIOHTTPServerPipelineConfiguration``, except that the upgrade configuration is not required -/// to be `Sendable`. -public struct NIOHTTPServerPipelineSynchronousConfiguration { - /// Whether to provide assistance handling HTTP clients that pipeline their requests. Defaults to `true`. If - /// `false`, users will need to handle clients that pipeline themselves. - public var pipeliningAssistance: Bool = true - - /// Whether to add a ``HTTPServerUpgradeHandler`` to the pipeline, configured for HTTP upgrade. Defaults to `nil`, - /// which will not add the handler to the pipeline. See the documentation on ``HTTPServerUpgradeHandler`` for more - /// details. - public var serverUpgrade: UpgradeConfiguration? = nil - - /// Whether to provide assistance handling protocol errors (e.g. failure to parse the HTTP request) by sending - /// 400 errors. Defaults to `true`. - public var errorHandling: Bool = true - - /// Whether to validate outbound response headers to confirm that they meet spec compliance. Defaults to `true`. - public var outboundHeaderValidation: Bool = true - - /// The configuration for the ``HTTPResponseEncoder``. Defaults to ``HTTPResponseEncoder/Configuration/init()``. - public var encoderConfiguration: HTTPResponseEncoder.Configuration = .init() - - /// The limit configuration for the ``HTTPDecoder``. Defaults to ``NIOHTTPDecoderLimitConfiguration/init()``. - public var decoderLimitConfiguration: NIOHTTPDecoderLimitConfiguration = .init() - - fileprivate init(_ configuration: NIOHTTPServerPipelineConfiguration) { - self.pipeliningAssistance = configuration.pipeliningAssistance - self.serverUpgrade = configuration.serverUpgrade.map { UpgradeConfiguration($0) } - self.errorHandling = configuration.errorHandling - self.outboundHeaderValidation = configuration.outboundHeaderValidation - self.encoderConfiguration = configuration.encoderConfiguration - self.decoderLimitConfiguration = configuration.decoderLimitConfiguration - } - - /// The configuration for HTTP upgrade. - public struct UpgradeConfiguration { - /// The upgraders the server supports, in order of preference. - public var upgraders: [HTTPServerProtocolUpgrader] - - /// Called once the upgrade is complete, with the context of the handler performing the upgrade. - public var completionHandler: (ChannelHandlerContext) -> Void - - /// Creates an upgrade configuration. - /// - /// - Parameters: - /// - upgraders: The upgraders the server supports, in order of preference. - /// - completionHandler: Called once the upgrade is complete, with the context of the handler performing - /// the upgrade. - public init( - upgraders: [HTTPServerProtocolUpgrader], - completionHandler: @escaping (ChannelHandlerContext) -> Void - ) { - self.upgraders = upgraders - self.completionHandler = completionHandler - } - - fileprivate init(_ configuration: NIOHTTPServerUpgradeConfiguration) { - self.init(upgraders: configuration.upgraders, completionHandler: configuration.completionHandler) - } - - fileprivate init(_ configuration: NIOHTTPServerPipelineConfiguration.UpgradeConfiguration) { - self.init(upgraders: configuration.upgraders, completionHandler: configuration.completionHandler) - } - } - - /// Creates a configuration with the default values. - public init() {} -} - -@available(*, unavailable) -extension NIOHTTPServerPipelineSynchronousConfiguration: Sendable {} diff --git a/Sources/NIOHTTP1Server/main.swift b/Sources/NIOHTTP1Server/main.swift index 2877c61ee..3e4a499bb 100644 --- a/Sources/NIOHTTP1Server/main.swift +++ b/Sources/NIOHTTP1Server/main.swift @@ -637,7 +637,7 @@ default: let fileIO = NonBlockingFileIO(threadPool: .singleton) func childChannelInitializer(channel: Channel) -> EventLoopFuture { - channel.pipeline.configureHTTPServerPipeline().flatMapThrowing { + channel.pipeline.configureHTTPServerPipeline(withErrorHandling: true).flatMapThrowing { try channel.pipeline.syncOperations.addHandler(HTTPHandler(fileIO: fileIO, htdocsPath: htdocs)) } } diff --git a/Sources/NIOPerformanceTester/main.swift b/Sources/NIOPerformanceTester/main.swift index ff9d908eb..9e4972860 100644 --- a/Sources/NIOPerformanceTester/main.swift +++ b/Sources/NIOPerformanceTester/main.swift @@ -190,7 +190,7 @@ let serverChannel = try ServerBootstrap(group: group) .serverChannelOption(.socketOption(.so_reuseaddr), value: 1) .childChannelInitializer { channel in channel.eventLoop.makeCompletedFuture { - try channel.pipeline.syncOperations.configureHTTPServerPipeline() + try channel.pipeline.syncOperations.configureHTTPServerPipeline(withPipeliningAssistance: true) try channel.pipeline.syncOperations.addHandler(SimpleHTTPServer()) } }.bind(host: "127.0.0.1", port: 0).wait() @@ -675,7 +675,10 @@ try measureAndPrint(desc: "no-net_http1_1k_reqs_1_conn") { } let sync = channel.pipeline.syncOperations - try sync.configureHTTPServerPipeline() + try sync.configureHTTPServerPipeline( + withPipeliningAssistance: true, + withErrorHandling: true + ) try sync.addHandler(SimpleHTTPServer()) try sync.addHandler(measuringHandler, position: .first) diff --git a/Tests/NIOHTTP1Tests/HTTPHeaderValidationTests.swift b/Tests/NIOHTTP1Tests/HTTPHeaderValidationTests.swift index 30fa3f739..2162713be 100644 --- a/Tests/NIOHTTP1Tests/HTTPHeaderValidationTests.swift +++ b/Tests/NIOHTTP1Tests/HTTPHeaderValidationTests.swift @@ -274,7 +274,7 @@ import Testing "!#$%&'*+-.^_`|~0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" let channel = EmbeddedChannel() - try channel.pipeline.syncOperations.configureHTTPServerPipeline(configuration: .noErrorHandling) + try channel.pipeline.syncOperations.configureHTTPServerPipeline(withErrorHandling: false) try channel.primeForResponse() let headers = HTTPHeaders([("Content-Length", "0"), (weirdAllowedFieldName, "present")]) @@ -294,7 +294,7 @@ import Testing let forbiddenFieldName = weirdAllowedFieldName + String(decoding: [byte], as: UTF8.self) let channel = EmbeddedChannel() - try channel.pipeline.syncOperations.configureHTTPServerPipeline(configuration: .noErrorHandling) + try channel.pipeline.syncOperations.configureHTTPServerPipeline(withErrorHandling: false) try channel.primeForResponse() let headers = HTTPHeaders([("Content-Length", "0"), (forbiddenFieldName, "present")]) @@ -328,7 +328,7 @@ import Testing "!#$%&'*+-.^_`|~0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" let channel = EmbeddedChannel() - try channel.pipeline.syncOperations.configureHTTPServerPipeline(configuration: .noErrorHandling) + try channel.pipeline.syncOperations.configureHTTPServerPipeline(withErrorHandling: false) try channel.primeForResponse() let headers = HTTPHeaders([("Transfer-Encoding", "chunked")]) @@ -353,7 +353,7 @@ import Testing let forbiddenFieldName = weirdAllowedFieldName + String(decoding: [byte], as: UTF8.self) let channel = EmbeddedChannel() - try channel.pipeline.syncOperations.configureHTTPServerPipeline(configuration: .noErrorHandling) + try channel.pipeline.syncOperations.configureHTTPServerPipeline(withErrorHandling: false) try channel.primeForResponse() try channel.writeOutbound(HTTPServerResponsePart.head(goodResponse)) @@ -375,7 +375,7 @@ import Testing "!\" \t#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~" let channel = EmbeddedChannel() - try channel.pipeline.syncOperations.configureHTTPServerPipeline(configuration: .noErrorHandling) + try channel.pipeline.syncOperations.configureHTTPServerPipeline(withErrorHandling: false) try channel.primeForResponse() let headers = HTTPHeaders([("Content-Length", "0"), ("Weird-Value", weirdAllowedFieldValue)]) @@ -396,7 +396,7 @@ import Testing let forbiddenFieldValue = weirdAllowedFieldValue + String(decoding: [byte], as: UTF8.self) let channel = EmbeddedChannel() - try channel.pipeline.syncOperations.configureHTTPServerPipeline(configuration: .noErrorHandling) + try channel.pipeline.syncOperations.configureHTTPServerPipeline(withErrorHandling: false) try channel.primeForResponse() let headers = HTTPHeaders([("Content-Length", "0"), ("Weird-Value", forbiddenFieldValue)]) @@ -417,7 +417,7 @@ import Testing let evenWeirderAllowedValue = weirdAllowedFieldValue + String(decoding: [byte], as: UTF8.self) let channel = EmbeddedChannel() - try channel.pipeline.syncOperations.configureHTTPServerPipeline(configuration: .noErrorHandling) + try channel.pipeline.syncOperations.configureHTTPServerPipeline(withErrorHandling: false) try channel.primeForResponse() let headers = HTTPHeaders([("Content-Length", "0"), ("Weird-Value", evenWeirderAllowedValue)]) @@ -439,7 +439,7 @@ import Testing "!\" \t#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~" let channel = EmbeddedChannel() - try channel.pipeline.syncOperations.configureHTTPServerPipeline(configuration: .noErrorHandling) + try channel.pipeline.syncOperations.configureHTTPServerPipeline(withErrorHandling: false) try channel.primeForResponse() let headers = HTTPHeaders([("Transfer-Encoding", "chunked")]) @@ -464,7 +464,7 @@ import Testing let forbiddenFieldValue = weirdAllowedFieldValue + String(decoding: [byte], as: UTF8.self) let channel = EmbeddedChannel() - try channel.pipeline.syncOperations.configureHTTPServerPipeline(configuration: .noErrorHandling) + try channel.pipeline.syncOperations.configureHTTPServerPipeline(withErrorHandling: false) try channel.primeForResponse() try channel.writeOutbound(HTTPServerResponsePart.head(goodResponse)) @@ -484,7 +484,7 @@ import Testing let evenWeirderAllowedValue = weirdAllowedFieldValue + String(decoding: [byte], as: UTF8.self) let channel = EmbeddedChannel() - try channel.pipeline.syncOperations.configureHTTPServerPipeline(configuration: .noErrorHandling) + try channel.pipeline.syncOperations.configureHTTPServerPipeline(withErrorHandling: false) try channel.primeForResponse() let weirdGoodTrailers = ByteBuffer(string: "0\r\nWeird-Value: \(evenWeirderAllowedValue)\r\n\r\n") @@ -692,7 +692,7 @@ import Testing let testReason = base + literalByteCanBeRepresented let channel = EmbeddedChannel() - try channel.pipeline.syncOperations.configureHTTPServerPipeline(configuration: .noErrorHandling) + try channel.pipeline.syncOperations.configureHTTPServerPipeline(withErrorHandling: false) try channel.primeForResponse() let response = HTTPResponseHead( @@ -732,7 +732,7 @@ import Testing @Test func responseIsDroppedIfHeadersInvalid() throws { let channel = EmbeddedChannel() - try channel.pipeline.syncOperations.configureHTTPServerPipeline(configuration: .noErrorHandling) + try channel.pipeline.syncOperations.configureHTTPServerPipeline(withErrorHandling: false) try channel.primeForResponse() // Read the first request. @@ -801,10 +801,10 @@ import Testing let invalidHeaderValue = "HeaderValueWith\rCR" let channel = EmbeddedChannel() - var configuration = NIOHTTPServerPipelineSynchronousConfiguration() - configuration.errorHandling = false - configuration.outboundHeaderValidation = false - try channel.pipeline.syncOperations.configureHTTPServerPipeline(configuration: configuration) + try channel.pipeline.syncOperations.configureHTTPServerPipeline( + withErrorHandling: false, + withOutboundHeaderValidation: false + ) try channel.primeForResponse() let headers = HTTPHeaders([ @@ -884,11 +884,3 @@ extension EmbeddedChannel { try self.writeInbound(request) } } - -extension NIOHTTPServerPipelineSynchronousConfiguration { - static var noErrorHandling: Self { - var configuration = Self() - configuration.errorHandling = false - return configuration - } -} diff --git a/Tests/NIOHTTP1Tests/HTTPResponseEncoderTest.swift b/Tests/NIOHTTP1Tests/HTTPResponseEncoderTest.swift index e2ebaf6b0..796f9a758 100644 --- a/Tests/NIOHTTP1Tests/HTTPResponseEncoderTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPResponseEncoderTest.swift @@ -269,7 +269,7 @@ class HTTPResponseEncoderTests: XCTestCase { } XCTAssertNoThrow( - try channel.pipeline.syncOperations.configureHTTPServerPipeline(configuration: .noFramingTransformation) + try channel.pipeline.configureHTTPServerPipeline(withEncoderConfiguration: .noFramingTransformation).wait() ) let request = ByteBuffer(string: "GET / HTTP/1.1\r\n\r\n") XCTAssertNoThrow(try channel.writeInbound(request)) @@ -292,7 +292,9 @@ class HTTPResponseEncoderTests: XCTestCase { } XCTAssertNoThrow( - try channel.pipeline.syncOperations.configureHTTPServerPipeline(configuration: .noFramingTransformation) + try channel.pipeline.syncOperations.configureHTTPServerPipeline( + withEncoderConfiguration: .noFramingTransformation + ) ) let request = ByteBuffer(string: "GET / HTTP/1.1\r\n\r\n") XCTAssertNoThrow(try channel.writeInbound(request)) @@ -315,7 +317,9 @@ class HTTPResponseEncoderTests: XCTestCase { } XCTAssertNoThrow( - try channel.pipeline.syncOperations.configureHTTPServerPipeline(configuration: .noFramingTransformation) + try channel.pipeline.syncOperations.configureHTTPServerPipeline( + withEncoderConfiguration: .noFramingTransformation + ) ) let request = ByteBuffer(string: "GET / HTTP/1.1\r\n\r\n") XCTAssertNoThrow(try channel.writeInbound(request)) @@ -353,7 +357,9 @@ class HTTPResponseEncoderTests: XCTestCase { } XCTAssertNoThrow( - try channel.pipeline.syncOperations.configureHTTPServerPipeline(configuration: .noFramingTransformation) + try channel.pipeline.syncOperations.configureHTTPServerPipeline( + withEncoderConfiguration: .noFramingTransformation + ) ) let request = ByteBuffer(string: "GET / HTTP/1.1\r\n\r\n") XCTAssertNoThrow(try channel.writeInbound(request)) @@ -609,11 +615,3 @@ class HTTPResponseEncoderTests: XCTestCase { XCTAssertNil(queue.popFirst()) } } - -extension NIOHTTPServerPipelineSynchronousConfiguration { - static var noFramingTransformation: Self { - var configuration = Self() - configuration.encoderConfiguration = .noFramingTransformation - return configuration - } -} diff --git a/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift b/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift index 5b23a4892..58ae3d76d 100644 --- a/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift @@ -396,7 +396,7 @@ class HTTPServerClientTest: XCTestCase { // Ensure we don't read faster than we can write by adding the BackPressureHandler into the pipeline. channel.eventLoop.makeCompletedFuture { let sync = channel.pipeline.syncOperations - try sync.configureHTTPServerPipeline(configuration: .noPipeliningAssistance) + try sync.configureHTTPServerPipeline(withPipeliningAssistance: false) let httpHandler = SimpleHTTPServer(mode) try sync.addHandlers(httpHandler) } @@ -469,12 +469,11 @@ class HTTPServerClientTest: XCTestCase { // Set the handlers that are appled to the accepted Channels .childChannelInitializer { channel in // Ensure we don't read faster than we can write by adding the BackPressureHandler into the pipeline. - channel.eventLoop.makeCompletedFuture { - try channel.pipeline.syncOperations.configureHTTPServerPipeline( - configuration: .noPipeliningAssistance - ) - let httpHandler = SimpleHTTPServer(mode) - return try channel.pipeline.syncOperations.addHandler(httpHandler) + channel.pipeline.configureHTTPServerPipeline(withPipeliningAssistance: false).flatMap { + channel.eventLoop.makeCompletedFuture { + let httpHandler = SimpleHTTPServer(mode) + return try channel.pipeline.syncOperations.addHandler(httpHandler) + } } }.bind(host: "127.0.0.1", port: 0).wait() ) @@ -545,7 +544,7 @@ class HTTPServerClientTest: XCTestCase { // Set the handlers that are appled to the accepted Channels .childChannelInitializer { channel in // Ensure we don't read faster than we can write by adding the BackPressureHandler into the pipeline. - channel.pipeline.configureHTTPServerPipeline().flatMap { + channel.pipeline.configureHTTPServerPipeline(withPipeliningAssistance: true).flatMap { channel.eventLoop.makeCompletedFuture { let httpHandler = SimpleHTTPServer(.byteBuffer) return try channel.pipeline.syncOperations.addHandler(httpHandler) @@ -617,12 +616,11 @@ class HTTPServerClientTest: XCTestCase { ServerBootstrap(group: group) .serverChannelOption(.socketOption(.so_reuseaddr), value: 1) .childChannelInitializer { channel in - channel.eventLoop.makeCompletedFuture { - try channel.pipeline.syncOperations.configureHTTPServerPipeline( - configuration: .noPipeliningAssistance - ) - let httpHandler = SimpleHTTPServer(mode) - return try channel.pipeline.syncOperations.addHandler(httpHandler) + channel.pipeline.configureHTTPServerPipeline(withPipeliningAssistance: false).flatMap { + channel.eventLoop.makeCompletedFuture { + let httpHandler = SimpleHTTPServer(mode) + return try channel.pipeline.syncOperations.addHandler(httpHandler) + } } }.bind(host: "127.0.0.1", port: 0).wait() ) @@ -692,12 +690,11 @@ class HTTPServerClientTest: XCTestCase { // Set the handlers that are appled to the accepted Channels .childChannelInitializer { channel in // Ensure we don't read faster than we can write by adding the BackPressureHandler into the pipeline. - channel.eventLoop.makeCompletedFuture { - try channel.pipeline.syncOperations.configureHTTPServerPipeline( - configuration: .noPipeliningAssistance - ) - let httpHandler = SimpleHTTPServer(mode) - return try channel.pipeline.syncOperations.addHandler(httpHandler) + channel.pipeline.configureHTTPServerPipeline(withPipeliningAssistance: false).flatMap { + channel.eventLoop.makeCompletedFuture { + let httpHandler = SimpleHTTPServer(mode) + return try channel.pipeline.syncOperations.addHandler(httpHandler) + } } }.bind(host: "127.0.0.1", port: 0).wait() ) @@ -738,12 +735,11 @@ class HTTPServerClientTest: XCTestCase { ServerBootstrap(group: group) .serverChannelOption(.socketOption(.so_reuseaddr), value: 1) .childChannelInitializer { channel in - channel.eventLoop.makeCompletedFuture { - try channel.pipeline.syncOperations.configureHTTPServerPipeline( - configuration: .noPipeliningAssistance - ) - let httpHandler = SimpleHTTPServer(.byteBuffer) - return try channel.pipeline.syncOperations.addHandler(httpHandler) + channel.pipeline.configureHTTPServerPipeline(withPipeliningAssistance: false).flatMap { + channel.eventLoop.makeCompletedFuture { + let httpHandler = SimpleHTTPServer(.byteBuffer) + return try channel.pipeline.syncOperations.addHandler(httpHandler) + } } }.bind(host: "127.0.0.1", port: 0).wait() ) @@ -795,12 +791,11 @@ class HTTPServerClientTest: XCTestCase { ServerBootstrap(group: group) .serverChannelOption(.socketOption(.so_reuseaddr), value: 1) .childChannelInitializer { channel in - channel.eventLoop.makeCompletedFuture { - try channel.pipeline.syncOperations.configureHTTPServerPipeline( - configuration: .noPipeliningAssistance - ) - let httpHandler = SimpleHTTPServer(.byteBuffer) - return try channel.pipeline.syncOperations.addHandler(httpHandler) + channel.pipeline.configureHTTPServerPipeline(withPipeliningAssistance: false).flatMap { + channel.eventLoop.makeCompletedFuture { + let httpHandler = SimpleHTTPServer(.byteBuffer) + return try channel.pipeline.syncOperations.addHandler(httpHandler) + } } }.bind(host: "127.0.0.1", port: 0).wait() ) @@ -847,11 +842,3 @@ class HTTPServerClientTest: XCTestCase { ) } } - -extension NIOHTTPServerPipelineSynchronousConfiguration { - static var noPipeliningAssistance: Self { - var configuration = Self() - configuration.pipeliningAssistance = false - return configuration - } -} diff --git a/Tests/NIOHTTP1Tests/HTTPServerPipelineSetupTests.swift b/Tests/NIOHTTP1Tests/HTTPServerPipelineSetupTests.swift deleted file mode 100644 index a22bd78dc..000000000 --- a/Tests/NIOHTTP1Tests/HTTPServerPipelineSetupTests.swift +++ /dev/null @@ -1,276 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the SwiftNIO open source project -// -// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors -// Licensed under Apache License v2.0 -// -// See LICENSE.txt for license information -// See CONTRIBUTORS.txt for the list of SwiftNIO project authors -// -// SPDX-License-Identifier: Apache-2.0 -// -//===----------------------------------------------------------------------===// - -import NIOCore -import NIOEmbedded -import NIOHTTP1 -import Testing - -@Suite struct HTTPServerPipelineSetupTests { - @Test(arguments: Options.all) - func configureHTTPServerPipeline(options: Options) throws { - try expectPipeline(NIOHTTPServerPipelineConfiguration.self, configuredWith: options) { channel, configuration in - try channel.pipeline.configureHTTPServerPipeline(configuration: configuration).wait() - } - } - - @Test(arguments: Options.all) - func syncConfigureHTTPServerPipeline(options: Options) throws { - try expectPipeline( - NIOHTTPServerPipelineSynchronousConfiguration.self, - configuredWith: options - ) { channel, configuration in - try channel.pipeline.syncOperations.configureHTTPServerPipeline(configuration: configuration) - } - } - - @available(*, deprecated, message: "Tests deprecated method") - @Test(arguments: Options.all) - func configureHTTPServerPipelineWithDeprecatedHelper(options: Options) throws { - try expectPipeline(NIOHTTPServerPipelineConfiguration.self, configuredWith: options) { channel, configuration in - try channel.pipeline.configureHTTPServerPipeline( - withPipeliningAssistance: configuration.pipeliningAssistance, - withServerUpgrade: configuration.serverUpgrade.map { ($0.upgraders, $0.completionHandler) }, - withErrorHandling: configuration.errorHandling, - withOutboundHeaderValidation: configuration.outboundHeaderValidation, - withEncoderConfiguration: configuration.encoderConfiguration, - withDecoderLimitConfiguration: configuration.decoderLimitConfiguration - ).wait() - } - } - - @available(*, deprecated, message: "Tests deprecated method") - @Test(arguments: Options.all) - func syncConfigureHTTPServerPipelineWithDeprecatedHelper(options: Options) throws { - try expectPipeline(NIOHTTPServerPipelineConfiguration.self, configuredWith: options) { channel, configuration in - try channel.pipeline.syncOperations.configureHTTPServerPipeline( - withPipeliningAssistance: configuration.pipeliningAssistance, - withServerUpgrade: configuration.serverUpgrade.map { ($0.upgraders, $0.completionHandler) }, - withErrorHandling: configuration.errorHandling, - withOutboundHeaderValidation: configuration.outboundHeaderValidation, - withEncoderConfiguration: configuration.encoderConfiguration, - withDecoderLimitConfiguration: configuration.decoderLimitConfiguration - ) - } - } -} - -extension HTTPServerPipelineSetupTests { - /// One combination of enabling or disabling each pipeline configuration setting. - struct Options: Sendable, CustomTestStringConvertible { - var pipeliningAssistance: Bool - var errorHandling: Bool - var outboundHeaderValidation: Bool - var serverUpgrade: Bool - var automaticallySetFramingHeaders: Bool - var customDecoderLimits: Bool - - /// Every combination of the options. - static let all: [Self] = (0..<64).map { bits in - Self( - pipeliningAssistance: bits & 1 != 0, - errorHandling: bits & 2 != 0, - outboundHeaderValidation: bits & 4 != 0, - serverUpgrade: bits & 8 != 0, - automaticallySetFramingHeaders: bits & 16 != 0, - customDecoderLimits: bits & 32 != 0 - ) - } - - var testDescription: String { - let enabled = [ - ("pipeliningAssistance", self.pipeliningAssistance), - ("errorHandling", self.errorHandling), - ("outboundHeaderValidation", self.outboundHeaderValidation), - ("serverUpgrade", self.serverUpgrade), - ("automaticallySetFramingHeaders", self.automaticallySetFramingHeaders), - ("customDecoderLimits", self.customDecoderLimits), - ].filter { $0.1 }.map { $0.0 } - return enabled.isEmpty ? "none" : enabled.joined(separator: ", ") - } - } -} - -/// Sets up a pipeline by applying `options` to a new `Configuration` and passing it to `configure`. Then checks that -/// the pipeline respects all the configurations in `options`. -private func expectPipeline( - _ configurationType: Configuration.Type, - configuredWith options: HTTPServerPipelineSetupTests.Options, - sourceLocation: SourceLocation = #_sourceLocation, - _ configure: (EmbeddedChannel, Configuration) throws -> Void -) throws { - var configuration = Configuration() - configuration.apply(options) - - func makeChannel() throws -> EmbeddedChannel { - let channel = EmbeddedChannel() - try configure(channel, configuration) - return channel - } - - try expectHandlers(in: makeChannel(), for: configuration, sourceLocation: sourceLocation) - try expectUpgrade(of: makeChannel(), serverUpgrade: options.serverUpgrade, sourceLocation: sourceLocation) - try expectEncoder(of: makeChannel(), using: configuration.encoderConfiguration, sourceLocation: sourceLocation) - try expectDecoder( - of: makeChannel(), - using: configuration.decoderLimitConfiguration, - errorHandling: configuration.errorHandling, - sourceLocation: sourceLocation - ) -} - -/// Checks that `channel`'s pipeline has the handlers that `configuration` enables. -private func expectHandlers( - in channel: EmbeddedChannel, - for configuration: some PipelineConfiguration, - sourceLocation: SourceLocation -) throws { - let sync = channel.pipeline.syncOperations - #expect( - sync.hasHandler(HTTPServerPipelineHandler.self) == configuration.pipeliningAssistance, - sourceLocation: sourceLocation - ) - #expect( - sync.hasHandler(HTTPServerProtocolErrorHandler.self) == configuration.errorHandling, - sourceLocation: sourceLocation - ) - #expect( - sync.hasHandler(NIOHTTPResponseHeadersValidator.self) == configuration.outboundHeaderValidation, - sourceLocation: sourceLocation - ) - _ = try channel.finish() -} - -/// Checks that `TestUpgrader` answers an upgrade request on `channel` when `serverUpgrade` is set. -private func expectUpgrade(of channel: EmbeddedChannel, serverUpgrade: Bool, sourceLocation: SourceLocation) throws { - let request = "OPTIONS * HTTP/1.1\r\nHost: localhost\r\nUpgrade: test\r\nConnection: upgrade\r\n\r\n" - try channel.writeInbound(ByteBuffer(string: request)) - channel.embeddedEventLoop.run() - let upgradeResponse = try channel.readOutbound(as: ByteBuffer.self) - if serverUpgrade { - let response = try #require(upgradeResponse, sourceLocation: sourceLocation) - let header = "\(TestUpgrader.testResponseHeader.name): \(TestUpgrader.testResponseHeader.value)" - #expect(String(buffer: response).contains(header), sourceLocation: sourceLocation) - } else { - #expect(upgradeResponse == nil, sourceLocation: sourceLocation) - } - _ = try channel.finish() -} - -/// Checks whether `encoderConfiguration` is applied. -private func expectEncoder( - of channel: EmbeddedChannel, - using encoderConfiguration: HTTPResponseEncoder.Configuration, - sourceLocation: SourceLocation -) throws { - try channel.writeInbound(ByteBuffer(string: "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n")) - try channel.writeOutbound(HTTPServerResponsePart.head(.init(version: .http1_1, status: .ok))) - let head = try #require(try channel.readOutbound(as: ByteBuffer.self), sourceLocation: sourceLocation) - #expect( - String(buffer: head).lowercased().contains("transfer-encoding: chunked") - == encoderConfiguration.automaticallySetFramingHeaders, - sourceLocation: sourceLocation - ) - _ = try? channel.finish() -} - -/// Checks whether `decoderLimitConfiguration` is applied. -private func expectDecoder( - of channel: EmbeddedChannel, - using decoderLimitConfiguration: NIOHTTPDecoderLimitConfiguration, - errorHandling: Bool, - sourceLocation: SourceLocation -) throws { - let value = String(repeating: "x", count: decoderLimitConfiguration.maxHeaderFieldSize + 1) - let error = #expect(throws: HTTPParserError.self, sourceLocation: sourceLocation) { - try channel.writeInbound(ByteBuffer(string: "GET / HTTP/1.1\r\nX-Hdr: \(value)\r\n\r\n")) - } - #expect(error == .headerOverflow, sourceLocation: sourceLocation) - let errorResponse = try channel.readOutbound(as: ByteBuffer.self) - if errorHandling { - let response = try #require(errorResponse, sourceLocation: sourceLocation) - #expect(String(buffer: response).hasPrefix("HTTP/1.1 400"), sourceLocation: sourceLocation) - } else { - #expect(errorResponse == nil, sourceLocation: sourceLocation) - } - _ = try? channel.finish() -} - -/// The settings required by `expectPipeline`. -private protocol PipelineConfiguration { - init() - - var pipeliningAssistance: Bool { get set } - var errorHandling: Bool { get set } - var outboundHeaderValidation: Bool { get set } - var encoderConfiguration: HTTPResponseEncoder.Configuration { get set } - var decoderLimitConfiguration: NIOHTTPDecoderLimitConfiguration { get set } - - mutating func setServerUpgrade(_ upgrade: NIOHTTPServerUpgradeSendableConfiguration) -} - -extension PipelineConfiguration { - fileprivate mutating func apply(_ options: HTTPServerPipelineSetupTests.Options) { - self.pipeliningAssistance = options.pipeliningAssistance - self.errorHandling = options.errorHandling - self.outboundHeaderValidation = options.outboundHeaderValidation - self.encoderConfiguration.automaticallySetFramingHeaders = options.automaticallySetFramingHeaders - if options.customDecoderLimits { - self.decoderLimitConfiguration.maxHeaderFieldSize = 128 - } - if options.serverUpgrade { - self.setServerUpgrade((upgraders: [TestUpgrader()], completionHandler: { _ in })) - } - } -} - -extension NIOHTTPServerPipelineConfiguration: PipelineConfiguration { - fileprivate mutating func setServerUpgrade(_ upgrade: NIOHTTPServerUpgradeSendableConfiguration) { - self.serverUpgrade = .init(upgraders: upgrade.upgraders, completionHandler: upgrade.completionHandler) - } -} - -extension NIOHTTPServerPipelineSynchronousConfiguration: PipelineConfiguration { - fileprivate mutating func setServerUpgrade(_ upgrade: NIOHTTPServerUpgradeSendableConfiguration) { - self.serverUpgrade = .init(upgraders: upgrade.upgraders, completionHandler: upgrade.completionHandler) - } -} - -private final class TestUpgrader: HTTPServerProtocolUpgrader, Sendable { - /// A header added to the upgrade response so that tests can determine whether this upgrader handled the upgrade. - static let testResponseHeader = (name: "test-upgrader", value: "upgraded") - - let supportedProtocol = "test" - let requiredUpgradeHeaders: [String] = [] - - func buildUpgradeResponse( - channel: Channel, - upgradeRequest: HTTPRequestHead, - initialResponseHeaders: HTTPHeaders - ) -> EventLoopFuture { - var headers = initialResponseHeaders - headers.add(name: Self.testResponseHeader.name, value: Self.testResponseHeader.value) - return channel.eventLoop.makeSucceededFuture(headers) - } - - func upgrade(context: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture { - context.eventLoop.makeSucceededVoidFuture() - } -} - -extension ChannelPipeline.SynchronousOperations { - fileprivate func hasHandler(_ of: Handler.Type) -> Bool { - (try? self.handler(type: of)) != nil - } -} diff --git a/Tests/NIOHTTP1Tests/HTTPServerProtocolErrorHandlerTest.swift b/Tests/NIOHTTP1Tests/HTTPServerProtocolErrorHandlerTest.swift index 26e19b0fc..8b277e373 100644 --- a/Tests/NIOHTTP1Tests/HTTPServerProtocolErrorHandlerTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPServerProtocolErrorHandlerTest.swift @@ -30,9 +30,7 @@ class HTTPServerProtocolErrorHandlerTest: XCTestCase { } } let channel = EmbeddedChannel() - XCTAssertNoThrow( - try channel.pipeline.syncOperations.configureHTTPServerPipeline(configuration: .withErrorHandling) - ) + XCTAssertNoThrow(try channel.pipeline.configureHTTPServerPipeline(withErrorHandling: true).wait()) XCTAssertNoThrow(try channel.pipeline.addHandler(CloseOnHTTPErrorHandler()).wait()) var buffer = channel.allocator.buffer(capacity: 1024) @@ -68,9 +66,7 @@ class HTTPServerProtocolErrorHandlerTest: XCTestCase { case error } let channel = EmbeddedChannel() - XCTAssertNoThrow( - try channel.pipeline.syncOperations.configureHTTPServerPipeline(configuration: .withErrorHandling) - ) + XCTAssertNoThrow(try channel.pipeline.configureHTTPServerPipeline(withErrorHandling: true).wait()) channel.pipeline.fireErrorCaught(DummyError.error) XCTAssertThrowsError(try channel.throwIfErrorCaught()) { error in @@ -86,9 +82,10 @@ class HTTPServerProtocolErrorHandlerTest: XCTestCase { XCTAssertNoThrow(try channel.finish()) } - var configuration = NIOHTTPServerPipelineSynchronousConfiguration.withErrorHandling - configuration.pipeliningAssistance = false - XCTAssertNoThrow(try channel.pipeline.syncOperations.configureHTTPServerPipeline(configuration: configuration)) + XCTAssertNoThrow( + try channel.pipeline.configureHTTPServerPipeline(withPipeliningAssistance: false, withErrorHandling: true) + .wait() + ) let res = HTTPServerResponsePart.head( .init( version: .http1_1, @@ -142,9 +139,7 @@ class HTTPServerProtocolErrorHandlerTest: XCTestCase { } let channel = EmbeddedChannel() - XCTAssertNoThrow( - try channel.pipeline.syncOperations.configureHTTPServerPipeline(configuration: .withErrorHandling) - ) + XCTAssertNoThrow(try channel.pipeline.syncOperations.configureHTTPServerPipeline(withErrorHandling: true)) XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(DelayWriteHandler())) var buffer = channel.allocator.buffer(capacity: 1024) @@ -176,9 +171,10 @@ class HTTPServerProtocolErrorHandlerTest: XCTestCase { let channel = EmbeddedChannel() defer { XCTAssertNoThrow(try channel.finish(acceptAlreadyClosed: false)) } - var configuration = NIOHTTPServerPipelineSynchronousConfiguration.withErrorHandling - configuration.pipeliningAssistance = false - XCTAssertNoThrow(try channel.pipeline.syncOperations.configureHTTPServerPipeline(configuration: configuration)) + XCTAssertNoThrow( + try channel.pipeline.configureHTTPServerPipeline(withPipeliningAssistance: false, withErrorHandling: true) + .wait() + ) XCTAssertNoThrow(try channel.connect(to: .makeAddressResolvingHost("127.0.0.1", port: 0)).wait()) // Send an head that expects a continue informational response @@ -217,10 +213,10 @@ class HTTPServerProtocolErrorHandlerTest: XCTestCase { defer { XCTAssertNoThrow(try channel.finish(acceptAlreadyClosed: false)) } XCTAssertNoThrow(try channel.connect(to: .makeAddressResolvingHost("127.0.0.1", port: 0)).wait()) - - var configuration = NIOHTTPServerPipelineSynchronousConfiguration.withErrorHandling - configuration.pipeliningAssistance = false - XCTAssertNoThrow(try channel.pipeline.syncOperations.configureHTTPServerPipeline(configuration: configuration)) + XCTAssertNoThrow( + try channel.pipeline.configureHTTPServerPipeline(withPipeliningAssistance: false, withErrorHandling: true) + .wait() + ) // Send an head that expects a continue informational response let reqHeadBytes = "POST / HTTP/1.1\r\nTransfer-Encoding: chunked\r\nExpect: 100-continue\r\n\r\n" @@ -261,11 +257,3 @@ class HTTPServerProtocolErrorHandlerTest: XCTestCase { } } - -extension NIOHTTPServerPipelineSynchronousConfiguration { - static var withErrorHandling: Self { - var configuration = Self() - configuration.errorHandling = true - return configuration - } -} diff --git a/Tests/NIOHTTP1Tests/HTTPServerUpgradeTests.swift b/Tests/NIOHTTP1Tests/HTTPServerUpgradeTests.swift index 5fbc1f508..9da6225cd 100644 --- a/Tests/NIOHTTP1Tests/HTTPServerUpgradeTests.swift +++ b/Tests/NIOHTTP1Tests/HTTPServerUpgradeTests.swift @@ -116,13 +116,11 @@ private func serverHTTPChannelWithAutoremoval( .serverChannelOption(.socketOption(.so_reuseaddr), value: 1) .childChannelInitializer { channel in p.succeed(channel) - var configuration = NIOHTTPServerPipelineConfiguration() - configuration.pipeliningAssistance = pipelining - configuration.serverUpgrade = .init( - upgraders: upgraders, - completionHandler: upgradeCompletionHandler - ) - return channel.pipeline.configureHTTPServerPipeline(configuration: configuration).flatMap { + let upgradeConfig = (upgraders: upgraders, completionHandler: upgradeCompletionHandler) + return channel.pipeline.configureHTTPServerPipeline( + withPipeliningAssistance: pipelining, + withServerUpgrade: upgradeConfig + ).flatMap { let futureResults = extraHandlers.map { channel.pipeline.addHandler($0) } return EventLoopFuture.andAllSucceed(futureResults, on: channel.eventLoop) } @@ -1023,9 +1021,11 @@ class HTTPServerUpgradeTestCase: XCTestCase { return delayedPromise.futureResult } - var configuration = NIOHTTPServerPipelineConfiguration() - configuration.serverUpgrade = .init(upgraders: [delayedUpgrader], completionHandler: { _ in }) - XCTAssertNoThrow(try channel.pipeline.configureHTTPServerPipeline(configuration: configuration).wait()) + XCTAssertNoThrow( + try channel.pipeline.configureHTTPServerPipeline( + withServerUpgrade: (upgraders: [delayedUpgrader], completionHandler: { context in }) + ).wait() + ) // Let's send in an upgrade request. let request = @@ -1080,12 +1080,13 @@ class HTTPServerUpgradeTestCase: XCTestCase { return myprotoPromise.futureResult } - var configuration = NIOHTTPServerPipelineConfiguration() - configuration.serverUpgrade = .init( - upgraders: [myprotoUpgrader, failingProtocolUpgrader], - completionHandler: { _ in } + XCTAssertNoThrow( + try channel.pipeline.configureHTTPServerPipeline( + withServerUpgrade: ( + upgraders: [myprotoUpgrader, failingProtocolUpgrader], completionHandler: { context in } + ) + ).wait() ) - XCTAssertNoThrow(try channel.pipeline.configureHTTPServerPipeline(configuration: configuration).wait()) // Let's send in an upgrade request. let request = @@ -1138,9 +1139,11 @@ class HTTPServerUpgradeTestCase: XCTestCase { return delayedPromise.futureResult } - var configuration = NIOHTTPServerPipelineConfiguration() - configuration.serverUpgrade = .init(upgraders: [delayedUpgrader], completionHandler: { _ in }) - XCTAssertNoThrow(try channel.pipeline.configureHTTPServerPipeline(configuration: configuration).wait()) + XCTAssertNoThrow( + try channel.pipeline.configureHTTPServerPipeline( + withServerUpgrade: (upgraders: [delayedUpgrader], completionHandler: { context in }) + ).wait() + ) // Let's send in an upgrade request. let request = @@ -1200,11 +1203,13 @@ class HTTPServerUpgradeTestCase: XCTestCase { return delayedPromise.futureResult } - var configuration = NIOHTTPServerPipelineConfiguration() // Here we're disabling the pipeline handler, because otherwise it makes this test case impossible to reach. - configuration.pipeliningAssistance = false - configuration.serverUpgrade = .init(upgraders: [delayedUpgrader], completionHandler: { _ in }) - XCTAssertNoThrow(try channel.pipeline.configureHTTPServerPipeline(configuration: configuration).wait()) + XCTAssertNoThrow( + try channel.pipeline.configureHTTPServerPipeline( + withPipeliningAssistance: false, + withServerUpgrade: (upgraders: [delayedUpgrader], completionHandler: { context in }) + ).wait() + ) // Let's send in an upgrade request. let request = @@ -1461,10 +1466,11 @@ class HTTPServerUpgradeTestCase: XCTestCase { defer { delayer.unblockUpgrade() } - - var configuration = NIOHTTPServerPipelineConfiguration() - configuration.serverUpgrade = .init(upgraders: [delayer], completionHandler: { _ in }) - XCTAssertNoThrow(try channel.pipeline.configureHTTPServerPipeline(configuration: configuration).wait()) + XCTAssertNoThrow( + try channel.pipeline.configureHTTPServerPipeline( + withServerUpgrade: (upgraders: [delayer], completionHandler: { context in }) + ).wait() + ) // Let's send in an upgrade request. let request = @@ -1523,9 +1529,11 @@ class HTTPServerUpgradeTestCase: XCTestCase { delayer.unblockUpgrade() } - var configuration = NIOHTTPServerPipelineConfiguration() - configuration.serverUpgrade = .init(upgraders: [delayer], completionHandler: { _ in }) - XCTAssertNoThrow(try channel.pipeline.configureHTTPServerPipeline(configuration: configuration).wait()) + XCTAssertNoThrow( + try channel.pipeline.configureHTTPServerPipeline( + withServerUpgrade: (upgraders: [delayer], completionHandler: { context in }) + ).wait() + ) // Let's send in an upgrade request. let request = diff --git a/Tests/NIOWebSocketTests/WebSocketServerEndToEndTests.swift b/Tests/NIOWebSocketTests/WebSocketServerEndToEndTests.swift index cb2e84099..438811e89 100644 --- a/Tests/NIOWebSocketTests/WebSocketServerEndToEndTests.swift +++ b/Tests/NIOWebSocketTests/WebSocketServerEndToEndTests.swift @@ -151,10 +151,14 @@ class WebSocketServerEndToEndTests: XCTestCase { upgradePipelineHandler: $0.upgradePipelineHandler ) } - - var configuration = NIOHTTPServerPipelineConfiguration() - configuration.serverUpgrade = .init(upgraders: upgraders, completionHandler: { _ in }) - XCTAssertNoThrow(try serverChannel.pipeline.configureHTTPServerPipeline(configuration: configuration).wait()) + XCTAssertNoThrow( + try serverChannel.pipeline.configureHTTPServerPipeline( + withServerUpgrade: ( + upgraders: upgraders, + completionHandler: { (context: ChannelHandlerContext) in } + ) + ).wait() + ) let clientChannel = EmbeddedChannel(loop: loop) return (loop: loop, serverChannel: serverChannel, clientChannel: clientChannel) }