mirror of
https://github.com/apple/swift-nio
synced 2026-11-26 04:57:49 +00:00
Introduce new typed HTTPServerUpgrader and WebSocketServerUpgrader (#2517)
* Introduce new typed `HTTPServerUpgrader` and `WebSocketServerUpgrader` # Motivation With our new `NIOAsyncChannel` and typed bootstrap APIs we want to be able to let users spell out their pipeline in a typed way. Pipelines can contain handlers that have to make a forking decision such as HTTP upgrading. Our current `HTTPServerUpgradeHandler` is one of those handlers but it lacks strict typing. To interact nicely with our new typed APIs we need to have a new variant of the `HTTPServerUpgradeHandler` that can carry type information. # Modification This PR adds a few things: 1. A new `NIOTypedHTTPServerUpgradeHandler` + `NIOTypedHTTPServeProtocolUpgrader`. I also moved the state handling logic to a separate state machine. I thought about unifying the state machines of the _old_ handler and the new one but they differ in behaviour which makes the state machine more complicated. 2. A new `NIOTypedWebSocketServerUpgrader` that conforms to `NIOTypedHTTPServerProtocolUpgrader` 3. An overhauled WebSocket server example that fully uses Concurrency. # Result We now have a way to fully type the server side of HTTP protocol upgrading. Code review Update parameter names for new API and fix example * Introduce new configuration struct and rename to `UpgradablePipeline` * Review comments
This commit is contained in:
1 parent
67553a7d6d
commit
de07e573d6
10 files changed
+1985
-381
No files matched your search
@@ -140,6 +140,7 @@ let package = Package(
|
||||
"NIOCore",
|
||||
"NIOConcurrencyHelpers",
|
||||
"CNIOLLHTTP",
|
||||
swiftCollections
|
||||
]
|
||||
),
|
||||
.target(
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
@_spi(AsyncChannel) import NIOCore
|
||||
|
||||
// MARK: - Server pipeline configuration
|
||||
|
||||
/// Configuration for an upgradable HTTP pipeline.
|
||||
@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *)
|
||||
@_spi(AsyncChannel)
|
||||
public struct NIOUpgradableHTTPServerPipelineConfiguration<UpgradeResult: 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 enablePipelining = true
|
||||
|
||||
/// Whether to provide assistance handling protocol errors (e.g. failure to parse the HTTP
|
||||
/// request) by sending 400 errors. Defaults to `true`.
|
||||
public var enableErrorHandling = true
|
||||
|
||||
/// Whether to validate outbound response headers to confirm that they are
|
||||
/// spec compliant. Defaults to `true`.
|
||||
public var enableResponseHeaderValidation = true
|
||||
|
||||
/// The configuration for the ``HTTPResponseEncoder``.
|
||||
public var httpResponseEncoderConfiguration = HTTPResponseEncoder.Configuration()
|
||||
|
||||
/// The configuration for the ``NIOTypedHTTPServerUpgradeHandler``.
|
||||
public var upgradeConfiguration: NIOTypedHTTPServerUpgradeConfiguration<UpgradeResult>
|
||||
|
||||
/// Initializes a new ``NIOUpgradableHTTPServerPipelineConfiguration`` with default values.
|
||||
///
|
||||
/// The current defaults provide the following features:
|
||||
/// 1. Assistance handling clients that pipeline HTTP requests.
|
||||
/// 2. Assistance handling protocol errors.
|
||||
/// 3. Outbound header fields validation to protect against response splitting attacks.
|
||||
/// 4. HTTP protocol upgrades.
|
||||
///
|
||||
/// The defaults will likely be extended in the future and we recommend to use this initializer to ensure
|
||||
/// you get newer features automatically.
|
||||
public init(
|
||||
upgradeConfiguration: NIOTypedHTTPServerUpgradeConfiguration<UpgradeResult>
|
||||
) {
|
||||
self.upgradeConfiguration = upgradeConfiguration
|
||||
}
|
||||
}
|
||||
|
||||
extension ChannelPipeline {
|
||||
/// Configure a `ChannelPipeline` for use as an HTTP server.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - configuration: The HTTP pipeline's configuration.
|
||||
/// - Returns: An `EventLoopFuture` that will fire when the pipeline is configured. The future contains an `EventLoopFuture`
|
||||
/// that is fired once the pipeline has been upgraded or not and contains the `UpgradeResult`.
|
||||
@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *)
|
||||
@_spi(AsyncChannel)
|
||||
public func configureUpgradableHTTPServerPipeline<UpgradeResult: Sendable>(
|
||||
configuration: NIOUpgradableHTTPServerPipelineConfiguration<UpgradeResult>
|
||||
) -> EventLoopFuture<EventLoopFuture<UpgradeResult>> {
|
||||
self._configureUpgradableHTTPServerPipeline(
|
||||
configuration: configuration
|
||||
)
|
||||
}
|
||||
|
||||
@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *)
|
||||
private func _configureUpgradableHTTPServerPipeline<UpgradeResult: Sendable>(
|
||||
configuration: NIOUpgradableHTTPServerPipelineConfiguration<UpgradeResult>
|
||||
) -> EventLoopFuture<EventLoopFuture<UpgradeResult>> {
|
||||
let future: EventLoopFuture<EventLoopFuture<UpgradeResult>>
|
||||
|
||||
if self.eventLoop.inEventLoop {
|
||||
let result = Result<EventLoopFuture<UpgradeResult>, Error> {
|
||||
try self.syncOperations.configureUpgradableHTTPServerPipeline(
|
||||
configuration: configuration
|
||||
)
|
||||
}
|
||||
future = self.eventLoop.makeCompletedFuture(result)
|
||||
} else {
|
||||
future = self.eventLoop.submit {
|
||||
try self.syncOperations.configureUpgradableHTTPServerPipeline(
|
||||
configuration: configuration
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return future
|
||||
}
|
||||
}
|
||||
|
||||
extension ChannelPipeline.SynchronousOperations {
|
||||
/// Configure a `ChannelPipeline` for use as an HTTP server.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - configuration: The HTTP pipeline's configuration.
|
||||
/// - Returns: An `EventLoopFuture` that is fired once the pipeline has been upgraded or not and contains the `UpgradeResult`.
|
||||
@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *)
|
||||
@_spi(AsyncChannel)
|
||||
public func configureUpgradableHTTPServerPipeline<UpgradeResult: Sendable>(
|
||||
configuration: NIOUpgradableHTTPServerPipelineConfiguration<UpgradeResult>
|
||||
) throws -> EventLoopFuture<UpgradeResult> {
|
||||
self.eventLoop.assertInEventLoop()
|
||||
|
||||
let responseEncoder = HTTPResponseEncoder(configuration: configuration.httpResponseEncoderConfiguration)
|
||||
let requestDecoder = ByteToMessageHandler(HTTPRequestDecoder(leftOverBytesStrategy: .forwardBytes))
|
||||
|
||||
var extraHTTPHandlers: [RemovableChannelHandler] = [requestDecoder]
|
||||
extraHTTPHandlers.reserveCapacity(3)
|
||||
|
||||
try self.addHandler(responseEncoder)
|
||||
try self.addHandler(requestDecoder)
|
||||
|
||||
if configuration.enablePipelining {
|
||||
let pipeliningHandler = HTTPServerPipelineHandler()
|
||||
try self.addHandler(pipeliningHandler)
|
||||
extraHTTPHandlers.append(pipeliningHandler)
|
||||
}
|
||||
|
||||
if configuration.enableResponseHeaderValidation {
|
||||
let headerValidationHandler = NIOHTTPResponseHeadersValidator()
|
||||
try self.addHandler(headerValidationHandler)
|
||||
extraHTTPHandlers.append(headerValidationHandler)
|
||||
}
|
||||
|
||||
if configuration.enableErrorHandling {
|
||||
let errorHandler = HTTPServerProtocolErrorHandler()
|
||||
try self.addHandler(errorHandler)
|
||||
extraHTTPHandlers.append(errorHandler)
|
||||
}
|
||||
|
||||
let upgrader = NIOTypedHTTPServerUpgradeHandler(
|
||||
httpEncoder: responseEncoder,
|
||||
extraHTTPHandlers: extraHTTPHandlers,
|
||||
upgradeConfiguration: configuration.upgradeConfiguration
|
||||
)
|
||||
try self.addHandler(upgrader)
|
||||
|
||||
return upgrader.upgradeResultFuture
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,373 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
@_spi(AsyncChannel) import NIOCore
|
||||
|
||||
/// An object that implements `NIOTypedHTTPServerProtocolUpgrader` knows how to handle HTTP upgrade to
|
||||
/// a protocol on a server-side channel.
|
||||
@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *)
|
||||
@_spi(AsyncChannel)
|
||||
public protocol NIOTypedHTTPServerProtocolUpgrader<UpgradeResult> {
|
||||
associatedtype UpgradeResult
|
||||
|
||||
/// The protocol this upgrader knows how to support.
|
||||
var supportedProtocol: String { get }
|
||||
|
||||
/// All the header fields the protocol needs in the request to successfully upgrade. These header fields
|
||||
/// will be provided to the handler when it is asked to handle the upgrade. They will also be validated
|
||||
/// against the inbound request's `Connection` header field.
|
||||
var requiredUpgradeHeaders: [String] { get }
|
||||
|
||||
/// Builds the upgrade response headers. Should return any headers that need to be supplied to the client
|
||||
/// in the 101 Switching Protocols response. If upgrade cannot proceed for any reason, this function should
|
||||
/// return a failed future.
|
||||
func buildUpgradeResponse(
|
||||
channel: Channel,
|
||||
upgradeRequest: HTTPRequestHead,
|
||||
initialResponseHeaders: HTTPHeaders
|
||||
) -> EventLoopFuture<HTTPHeaders>
|
||||
|
||||
/// Called when the upgrade response has been flushed. At this time it is safe to mutate the channel pipeline
|
||||
/// to add whatever channel handlers are required. Until the returned `EventLoopFuture` succeeds, all received
|
||||
/// data will be buffered.
|
||||
func upgrade(
|
||||
channel: Channel,
|
||||
upgradeRequest: HTTPRequestHead
|
||||
) -> EventLoopFuture<UpgradeResult>
|
||||
}
|
||||
|
||||
/// The upgrade configuration for the ``NIOTypedHTTPServerUpgradeHandler``.
|
||||
@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *)
|
||||
@_spi(AsyncChannel)
|
||||
public struct NIOTypedHTTPServerUpgradeConfiguration<UpgradeResult: Sendable> {
|
||||
/// The array of potential upgraders.
|
||||
public var upgraders: [any NIOTypedHTTPServerProtocolUpgrader<UpgradeResult>]
|
||||
|
||||
/// A closure that is run once it is determined that no protocol upgrade is happening. This can be used
|
||||
/// to configure handlers that expect HTTP.
|
||||
public var notUpgradingCompletionHandler: @Sendable (Channel) -> EventLoopFuture<UpgradeResult>
|
||||
|
||||
public init(
|
||||
upgraders: [any NIOTypedHTTPServerProtocolUpgrader<UpgradeResult>],
|
||||
notUpgradingCompletionHandler: @Sendable @escaping (Channel) -> EventLoopFuture<UpgradeResult>
|
||||
) {
|
||||
self.upgraders = upgraders
|
||||
self.notUpgradingCompletionHandler = notUpgradingCompletionHandler
|
||||
}
|
||||
}
|
||||
|
||||
/// A server-side channel handler that receives HTTP requests and optionally performs an HTTP-upgrade.
|
||||
///
|
||||
/// Removes itself from the channel pipeline after the first inbound request on the connection, regardless of
|
||||
/// whether the upgrade succeeded or not.
|
||||
///
|
||||
/// This handler behaves a bit differently from its Netty counterpart because it does not allow upgrade
|
||||
/// on any request but the first on a connection. This is primarily to handle clients that pipeline: it's
|
||||
/// sufficiently difficult to ensure that the upgrade happens at a safe time while dealing with pipelined
|
||||
/// requests that we choose to punt on it entirely and not allow it. As it happens this is mostly fine:
|
||||
/// the odds of someone needing to upgrade midway through the lifetime of a connection are very low.
|
||||
@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *)
|
||||
@_spi(AsyncChannel)
|
||||
public final class NIOTypedHTTPServerUpgradeHandler<UpgradeResult: Sendable>: ChannelInboundHandler, RemovableChannelHandler {
|
||||
public typealias InboundIn = HTTPServerRequestPart
|
||||
public typealias InboundOut = HTTPServerRequestPart
|
||||
public typealias OutboundOut = HTTPServerResponsePart
|
||||
|
||||
private let upgraders: [String: any NIOTypedHTTPServerProtocolUpgrader<UpgradeResult>]
|
||||
private let notUpgradingCompletionHandler: @Sendable (Channel) -> EventLoopFuture<UpgradeResult>
|
||||
private let httpEncoder: HTTPResponseEncoder
|
||||
private let extraHTTPHandlers: [RemovableChannelHandler]
|
||||
private var stateMachine = NIOTypedHTTPServerUpgraderStateMachine<UpgradeResult>()
|
||||
|
||||
private var _upgradeResultPromise: EventLoopPromise<UpgradeResult>?
|
||||
private var upgradeResultPromise: EventLoopPromise<UpgradeResult> {
|
||||
precondition(
|
||||
self._upgradeResultPromise != nil,
|
||||
"Tried to access the upgrade result before the handler was added to a pipeline"
|
||||
)
|
||||
return self._upgradeResultPromise!
|
||||
}
|
||||
|
||||
/// The upgrade future which will be completed once protocol upgrading has been done.
|
||||
public var upgradeResultFuture: EventLoopFuture<UpgradeResult> {
|
||||
self.upgradeResultPromise.futureResult
|
||||
}
|
||||
|
||||
/// Create a ``NIOTypedHTTPServerUpgradeHandler``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - httpEncoder: The ``HTTPResponseEncoder`` encoding responses from this handler and which will
|
||||
/// be removed from the pipeline once the upgrade response is sent. This is used to ensure
|
||||
/// that the pipeline will be in a clean state after upgrade.
|
||||
/// - extraHTTPHandlers: Any other handlers that are directly related to handling HTTP. At the very least
|
||||
/// this should include the `HTTPDecoder`, but should also include any other handler that cannot tolerate
|
||||
/// receiving non-HTTP data.
|
||||
/// - upgradeConfiguration: The upgrade configuration.
|
||||
public init(
|
||||
httpEncoder: HTTPResponseEncoder,
|
||||
extraHTTPHandlers: [RemovableChannelHandler],
|
||||
upgradeConfiguration: NIOTypedHTTPServerUpgradeConfiguration<UpgradeResult>
|
||||
) {
|
||||
var upgraderMap = [String: any NIOTypedHTTPServerProtocolUpgrader<UpgradeResult>]()
|
||||
for upgrader in upgradeConfiguration.upgraders {
|
||||
upgraderMap[upgrader.supportedProtocol.lowercased()] = upgrader
|
||||
}
|
||||
self.upgraders = upgraderMap
|
||||
self.notUpgradingCompletionHandler = upgradeConfiguration.notUpgradingCompletionHandler
|
||||
self.httpEncoder = httpEncoder
|
||||
self.extraHTTPHandlers = extraHTTPHandlers
|
||||
}
|
||||
|
||||
public func handlerAdded(context: ChannelHandlerContext) {
|
||||
self._upgradeResultPromise = context.eventLoop.makePromise(of: UpgradeResult.self)
|
||||
}
|
||||
|
||||
public func handlerRemoved(context: ChannelHandlerContext) {
|
||||
switch self.stateMachine.handlerRemoved() {
|
||||
case .failUpgradePromise:
|
||||
self.upgradeResultPromise.fail(ChannelError.inappropriateOperationForState)
|
||||
case .none:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
|
||||
switch self.stateMachine.channelReadData(data) {
|
||||
case .unwrapData:
|
||||
let requestPart = self.unwrapInboundIn(data)
|
||||
self.channelRead(context: context, requestPart: requestPart)
|
||||
|
||||
case .fireChannelRead:
|
||||
context.fireChannelRead(data)
|
||||
|
||||
case .none:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
private func channelRead(context: ChannelHandlerContext, requestPart: HTTPServerRequestPart) {
|
||||
switch self.stateMachine.channelReadRequestPart(requestPart) {
|
||||
case .failUpgradePromise(let error):
|
||||
self.upgradeResultPromise.fail(error)
|
||||
|
||||
case .runNotUpgradingInitializer:
|
||||
self.notUpgradingCompletionHandler(context.channel)
|
||||
.hop(to: context.eventLoop)
|
||||
.whenComplete { result in
|
||||
self.upgradingHandlerCompleted(context: context, result, requestHeadAndProtocol: nil)
|
||||
}
|
||||
|
||||
case .findUpgrader(let head, let requestedProtocols, let allHeaderNames, let connectionHeader):
|
||||
let protocolIterator = requestedProtocols.makeIterator()
|
||||
self.handleUpgradeForProtocol(
|
||||
context: context,
|
||||
protocolIterator: protocolIterator,
|
||||
request: head,
|
||||
allHeaderNames: allHeaderNames,
|
||||
connectionHeader: connectionHeader
|
||||
).whenComplete { result in
|
||||
context.eventLoop.assertInEventLoop()
|
||||
self.findingUpgradeCompleted(context: context, requestHead: head, result)
|
||||
}
|
||||
|
||||
case .startUpgrading(let upgrader, let requestHead, let responseHeaders, let proto):
|
||||
self.startUpgrading(
|
||||
context: context,
|
||||
upgrader: upgrader,
|
||||
requestHead: requestHead,
|
||||
responseHeaders: responseHeaders,
|
||||
proto: proto
|
||||
)
|
||||
|
||||
case .none:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
private func upgradingHandlerCompleted(
|
||||
context: ChannelHandlerContext,
|
||||
_ result: Result<UpgradeResult, Error>,
|
||||
requestHeadAndProtocol: (HTTPRequestHead, String)?
|
||||
) {
|
||||
switch self.stateMachine.upgradingHandlerCompleted(result) {
|
||||
case .fireErrorCaughtAndRemoveHandler(let error):
|
||||
self.upgradeResultPromise.fail(error)
|
||||
context.fireErrorCaught(error)
|
||||
context.pipeline.removeHandler(self, promise: nil)
|
||||
|
||||
case .fireErrorCaughtAndStartUnbuffering(let error):
|
||||
self.upgradeResultPromise.fail(error)
|
||||
context.fireErrorCaught(error)
|
||||
self.unbuffer(context: context)
|
||||
|
||||
case .startUnbuffering(let value):
|
||||
if let requestHeadAndProtocol = requestHeadAndProtocol {
|
||||
context.fireUserInboundEventTriggered(HTTPServerUpgradeEvents.upgradeComplete(toProtocol: requestHeadAndProtocol.1, upgradeRequest: requestHeadAndProtocol.0))
|
||||
}
|
||||
self.upgradeResultPromise.succeed(value)
|
||||
self.unbuffer(context: context)
|
||||
|
||||
case .removeHandler(let value):
|
||||
if let requestHeadAndProtocol = requestHeadAndProtocol {
|
||||
context.fireUserInboundEventTriggered(HTTPServerUpgradeEvents.upgradeComplete(toProtocol: requestHeadAndProtocol.1, upgradeRequest: requestHeadAndProtocol.0))
|
||||
}
|
||||
self.upgradeResultPromise.succeed(value)
|
||||
context.pipeline.removeHandler(self, promise: nil)
|
||||
|
||||
case .none:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
/// Attempt to upgrade a single protocol.
|
||||
///
|
||||
/// Will recurse through `protocolIterator` if upgrade fails.
|
||||
private func handleUpgradeForProtocol(
|
||||
context: ChannelHandlerContext,
|
||||
protocolIterator: Array<String>.Iterator,
|
||||
request: HTTPRequestHead,
|
||||
allHeaderNames: Set<String>,
|
||||
connectionHeader: Set<String>
|
||||
) -> EventLoopFuture<(upgrader: any NIOTypedHTTPServerProtocolUpgrader<UpgradeResult>, responseHeaders: HTTPHeaders, proto: String)?> {
|
||||
// We want a local copy of the protocol iterator. We'll pass it to the next invocation of the function.
|
||||
var protocolIterator = protocolIterator
|
||||
guard let proto = protocolIterator.next() else {
|
||||
// We're done! No suitable protocol for upgrade.
|
||||
return context.eventLoop.makeSucceededFuture(nil)
|
||||
}
|
||||
|
||||
guard let upgrader = self.upgraders[proto.lowercased()] else {
|
||||
return self.handleUpgradeForProtocol(context: context, protocolIterator: protocolIterator, request: request, allHeaderNames: allHeaderNames, connectionHeader: connectionHeader)
|
||||
}
|
||||
|
||||
let requiredHeaders = Set(upgrader.requiredUpgradeHeaders.map { $0.lowercased() })
|
||||
guard requiredHeaders.isSubset(of: allHeaderNames) && requiredHeaders.isSubset(of: connectionHeader) else {
|
||||
return self.handleUpgradeForProtocol(context: context, protocolIterator: protocolIterator, request: request, allHeaderNames: allHeaderNames, connectionHeader: connectionHeader)
|
||||
}
|
||||
|
||||
let responseHeaders = self.buildUpgradeHeaders(protocol: proto)
|
||||
return upgrader.buildUpgradeResponse(
|
||||
channel: context.channel,
|
||||
upgradeRequest: request,
|
||||
initialResponseHeaders: responseHeaders
|
||||
)
|
||||
.hop(to: context.eventLoop)
|
||||
.map { (upgrader, $0, proto) }
|
||||
.flatMapError { error in
|
||||
// No upgrade here. We want to fire the error down the pipeline, and then try another loop iteration.
|
||||
context.fireErrorCaught(error)
|
||||
return self.handleUpgradeForProtocol(context: context, protocolIterator: protocolIterator, request: request, allHeaderNames: allHeaderNames, connectionHeader: connectionHeader)
|
||||
}
|
||||
}
|
||||
|
||||
private func findingUpgradeCompleted(
|
||||
context: ChannelHandlerContext,
|
||||
requestHead: HTTPRequestHead,
|
||||
_ result: Result<(upgrader: any NIOTypedHTTPServerProtocolUpgrader<UpgradeResult>, responseHeaders: HTTPHeaders, proto: String)?, Error>
|
||||
) {
|
||||
switch self.stateMachine.findingUpgraderCompleted(requestHead: requestHead, result) {
|
||||
case .startUpgrading(let upgrader, let responseHeaders, let proto):
|
||||
self.startUpgrading(
|
||||
context: context,
|
||||
upgrader: upgrader,
|
||||
requestHead: requestHead,
|
||||
responseHeaders: responseHeaders,
|
||||
proto: proto
|
||||
)
|
||||
|
||||
case .runNotUpgradingInitializer:
|
||||
self.notUpgradingCompletionHandler(context.channel)
|
||||
.hop(to: context.eventLoop)
|
||||
.whenComplete { result in
|
||||
self.upgradingHandlerCompleted(context: context, result, requestHeadAndProtocol: nil)
|
||||
}
|
||||
|
||||
case .fireErrorCaughtAndStartUnbuffering(let error):
|
||||
self.upgradeResultPromise.fail(error)
|
||||
context.fireErrorCaught(error)
|
||||
self.unbuffer(context: context)
|
||||
|
||||
case .fireErrorCaughtAndRemoveHandler(let error):
|
||||
self.upgradeResultPromise.fail(error)
|
||||
context.fireErrorCaught(error)
|
||||
context.pipeline.removeHandler(self, promise: nil)
|
||||
|
||||
case .none:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
private func startUpgrading(
|
||||
context: ChannelHandlerContext,
|
||||
upgrader: any NIOTypedHTTPServerProtocolUpgrader<UpgradeResult>,
|
||||
requestHead: HTTPRequestHead,
|
||||
responseHeaders: HTTPHeaders,
|
||||
proto: String
|
||||
) {
|
||||
// Before we finish the upgrade we have to remove the HTTPDecoder and any other non-Encoder HTTP
|
||||
// handlers from the pipeline, to prevent them parsing any more data. We'll buffer the data until
|
||||
// that completes.
|
||||
// While there are a lot of Futures involved here it's quite possible that all of this code will
|
||||
// actually complete synchronously: we just want to program for the possibility that it won't.
|
||||
// Once that's done, we send the upgrade response, then remove the HTTP encoder, then call the
|
||||
// internal handler, then call the user code, and then finally when the user code is done we do
|
||||
// our final cleanup steps, namely we replay the received data we buffered in the meantime and
|
||||
// then remove ourselves from the pipeline.
|
||||
self.removeExtraHandlers(context: context).flatMap {
|
||||
self.sendUpgradeResponse(context: context, responseHeaders: responseHeaders)
|
||||
}.flatMap {
|
||||
context.pipeline.removeHandler(self.httpEncoder)
|
||||
}.flatMap { () -> EventLoopFuture<UpgradeResult> in
|
||||
return upgrader.upgrade(channel: context.channel, upgradeRequest: requestHead)
|
||||
}.hop(to: context.eventLoop)
|
||||
.whenComplete { result in
|
||||
self.upgradingHandlerCompleted(context: context, result, requestHeadAndProtocol: (requestHead, proto))
|
||||
}
|
||||
}
|
||||
|
||||
/// Sends the 101 Switching Protocols response for the pipeline.
|
||||
private func sendUpgradeResponse(context: ChannelHandlerContext, responseHeaders: HTTPHeaders) -> EventLoopFuture<Void> {
|
||||
var response = HTTPResponseHead(version: .http1_1, status: .switchingProtocols)
|
||||
response.headers = responseHeaders
|
||||
return context.writeAndFlush(wrapOutboundOut(HTTPServerResponsePart.head(response)))
|
||||
}
|
||||
|
||||
/// Builds the initial mandatory HTTP headers for HTTP upgrade responses.
|
||||
private func buildUpgradeHeaders(`protocol`: String) -> HTTPHeaders {
|
||||
return HTTPHeaders([("connection", "upgrade"), ("upgrade", `protocol`)])
|
||||
}
|
||||
|
||||
/// Removes any extra HTTP-related handlers from the channel pipeline.
|
||||
private func removeExtraHandlers(context: ChannelHandlerContext) -> EventLoopFuture<Void> {
|
||||
guard self.extraHTTPHandlers.count > 0 else {
|
||||
return context.eventLoop.makeSucceededFuture(())
|
||||
}
|
||||
|
||||
return .andAllSucceed(self.extraHTTPHandlers.map { context.pipeline.removeHandler($0) },
|
||||
on: context.eventLoop)
|
||||
}
|
||||
|
||||
private func unbuffer(context: ChannelHandlerContext) {
|
||||
while true {
|
||||
switch self.stateMachine.unbuffer() {
|
||||
case .fireChannelRead(let data):
|
||||
context.fireChannelRead(data)
|
||||
|
||||
case .fireChannelReadCompleteAndRemoveHandler:
|
||||
context.fireChannelReadComplete()
|
||||
context.pipeline.removeHandler(self, promise: nil)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,385 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2023 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import DequeModule
|
||||
import NIOCore
|
||||
|
||||
@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *)
|
||||
struct NIOTypedHTTPServerUpgraderStateMachine<UpgradeResult> {
|
||||
@usableFromInline
|
||||
enum State {
|
||||
/// The state before we received a TLSUserEvent. We are just forwarding any read at this point.
|
||||
case initial
|
||||
|
||||
@usableFromInline
|
||||
struct AwaitingUpgrader {
|
||||
var seenFirstRequest: Bool
|
||||
var buffer: Deque<NIOAny>
|
||||
}
|
||||
|
||||
/// The request head has been received. We're currently running the future chain awaiting an upgrader.
|
||||
case awaitingUpgrader(AwaitingUpgrader)
|
||||
|
||||
@usableFromInline
|
||||
struct UpgraderReady {
|
||||
var upgrader: any NIOTypedHTTPServerProtocolUpgrader<UpgradeResult>
|
||||
var requestHead: HTTPRequestHead
|
||||
var responseHeaders: HTTPHeaders
|
||||
var proto: String
|
||||
var buffer: Deque<NIOAny>
|
||||
}
|
||||
|
||||
/// We have an upgrader, which means we can begin upgrade we are just waiting for the request end.
|
||||
case upgraderReady(UpgraderReady)
|
||||
|
||||
@usableFromInline
|
||||
struct Upgrading {
|
||||
var buffer: Deque<NIOAny>
|
||||
}
|
||||
/// We are either running the upgrading handler.
|
||||
case upgrading(Upgrading)
|
||||
|
||||
@usableFromInline
|
||||
struct Unbuffering {
|
||||
var buffer: Deque<NIOAny>
|
||||
}
|
||||
case unbuffering(Unbuffering)
|
||||
|
||||
case finished
|
||||
|
||||
case modifying
|
||||
}
|
||||
|
||||
private var state = State.initial
|
||||
|
||||
@usableFromInline
|
||||
enum HandlerRemovedAction {
|
||||
case failUpgradePromise
|
||||
}
|
||||
|
||||
@inlinable
|
||||
mutating func handlerRemoved() -> HandlerRemovedAction? {
|
||||
switch self.state {
|
||||
case .initial, .awaitingUpgrader, .upgraderReady, .upgrading, .unbuffering:
|
||||
self.state = .finished
|
||||
return .failUpgradePromise
|
||||
|
||||
case .finished:
|
||||
return .none
|
||||
|
||||
case .modifying:
|
||||
fatalError("Internal inconsistency in HTTPServerUpgradeStateMachine")
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
enum ChannelReadDataAction {
|
||||
case unwrapData
|
||||
case fireChannelRead
|
||||
}
|
||||
|
||||
@inlinable
|
||||
mutating func channelReadData(_ data: NIOAny) -> ChannelReadDataAction? {
|
||||
switch self.state {
|
||||
case .initial:
|
||||
return .unwrapData
|
||||
|
||||
case .awaitingUpgrader(var awaitingUpgrader):
|
||||
if awaitingUpgrader.seenFirstRequest {
|
||||
// We should buffer the data since we have seen the full request.
|
||||
self.state = .modifying
|
||||
awaitingUpgrader.buffer.append(data)
|
||||
self.state = .awaitingUpgrader(awaitingUpgrader)
|
||||
return nil
|
||||
} else {
|
||||
// We shouldn't buffer. This means we are still expecting HTTP parts.
|
||||
return .unwrapData
|
||||
}
|
||||
|
||||
case .upgraderReady:
|
||||
// We have not seen the end of the HTTP request so this
|
||||
// data is probably an HTTP request part.
|
||||
return .unwrapData
|
||||
|
||||
case .unbuffering(var unbuffering):
|
||||
self.state = .modifying
|
||||
unbuffering.buffer.append(data)
|
||||
self.state = .unbuffering(unbuffering)
|
||||
return nil
|
||||
|
||||
case .finished:
|
||||
return .fireChannelRead
|
||||
|
||||
case .upgrading(var upgrading):
|
||||
// We got a read while running ugprading.
|
||||
// We have to buffer the read to unbuffer it afterwards
|
||||
self.state = .modifying
|
||||
upgrading.buffer.append(data)
|
||||
self.state = .upgrading(upgrading)
|
||||
return nil
|
||||
|
||||
case .modifying:
|
||||
fatalError("Internal inconsistency in HTTPServerUpgradeStateMachine")
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
enum ChannelReadRequestPartAction {
|
||||
case failUpgradePromise(Error)
|
||||
case runNotUpgradingInitializer
|
||||
case startUpgrading(
|
||||
upgrader: any NIOTypedHTTPServerProtocolUpgrader<UpgradeResult>,
|
||||
requestHead: HTTPRequestHead,
|
||||
responseHeaders: HTTPHeaders,
|
||||
proto: String
|
||||
)
|
||||
case findUpgrader(
|
||||
head: HTTPRequestHead,
|
||||
requestedProtocols: [String],
|
||||
allHeaderNames: Set<String>,
|
||||
connectionHeader: Set<String>
|
||||
)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
mutating func channelReadRequestPart(_ requestPart: HTTPServerRequestPart) -> ChannelReadRequestPartAction? {
|
||||
switch self.state {
|
||||
case .initial:
|
||||
guard case .head(let head) = requestPart else {
|
||||
// The first data that we saw was not a head. This is a protocol error and we are just going to
|
||||
// fail upgrading
|
||||
return .failUpgradePromise(HTTPServerUpgradeErrors.invalidHTTPOrdering)
|
||||
}
|
||||
|
||||
// Ok, we have a HTTP head. Check if it's an upgrade.
|
||||
let requestedProtocols = head.headers[canonicalForm: "upgrade"].map(String.init)
|
||||
guard requestedProtocols.count > 0 else {
|
||||
// We have to buffer now since we got the request head but are not upgrading.
|
||||
// The user is configuring the HTTP pipeline now.
|
||||
var buffer = Deque<NIOAny>()
|
||||
buffer.append(NIOAny(requestPart))
|
||||
self.state = .upgrading(.init(buffer: buffer))
|
||||
return .runNotUpgradingInitializer
|
||||
}
|
||||
|
||||
// We can now transition to awaiting the upgrader. This means that we are trying to
|
||||
// find an upgrade that can handle requested protocols. We are not buffering because
|
||||
// we are waiting for the request end.
|
||||
self.state = .awaitingUpgrader(.init(seenFirstRequest: false, buffer: .init()))
|
||||
|
||||
let connectionHeader = Set(head.headers[canonicalForm: "connection"].map { $0.lowercased() })
|
||||
let allHeaderNames = Set(head.headers.map { $0.name.lowercased() })
|
||||
|
||||
return .findUpgrader(
|
||||
head: head,
|
||||
requestedProtocols: requestedProtocols,
|
||||
allHeaderNames: allHeaderNames,
|
||||
connectionHeader: connectionHeader
|
||||
)
|
||||
|
||||
case .awaitingUpgrader(let awaitingUpgrader):
|
||||
switch (awaitingUpgrader.seenFirstRequest, requestPart) {
|
||||
case (true, _):
|
||||
// This is weird we are seeing more requests parts after we have seen an end
|
||||
// Let's fail upgrading
|
||||
return .failUpgradePromise(HTTPServerUpgradeErrors.invalidHTTPOrdering)
|
||||
|
||||
case (false, .head):
|
||||
// This is weird we are seeing another head but haven't seen the end for the request before
|
||||
return .failUpgradePromise(HTTPServerUpgradeErrors.invalidHTTPOrdering)
|
||||
|
||||
case (false, .body):
|
||||
// This is weird we are seeing body parts for a request that indicated that it wanted
|
||||
// to upgrade.
|
||||
return .failUpgradePromise(HTTPServerUpgradeErrors.invalidHTTPOrdering)
|
||||
|
||||
case (false, .end):
|
||||
// Okay we got the end as expected. Just gotta store this in our state.
|
||||
self.state = .awaitingUpgrader(.init(seenFirstRequest: true, buffer: awaitingUpgrader.buffer))
|
||||
return nil
|
||||
}
|
||||
|
||||
case .upgraderReady(let upgraderReady):
|
||||
switch requestPart {
|
||||
case .head:
|
||||
// This is weird we are seeing another head but haven't seen the end for the request before
|
||||
return .failUpgradePromise(HTTPServerUpgradeErrors.invalidHTTPOrdering)
|
||||
|
||||
case .body:
|
||||
// This is weird we are seeing body parts for a request that indicated that it wanted
|
||||
// to upgrade.
|
||||
return .failUpgradePromise(HTTPServerUpgradeErrors.invalidHTTPOrdering)
|
||||
|
||||
case .end:
|
||||
// Okay we got the end as expected and our upgrader is ready so let's start upgrading
|
||||
self.state = .upgrading(.init(buffer: upgraderReady.buffer))
|
||||
return .startUpgrading(
|
||||
upgrader: upgraderReady.upgrader,
|
||||
requestHead: upgraderReady.requestHead,
|
||||
responseHeaders: upgraderReady.responseHeaders,
|
||||
proto: upgraderReady.proto
|
||||
)
|
||||
}
|
||||
|
||||
case .upgrading, .unbuffering, .finished:
|
||||
fatalError("Internal inconsistency in HTTPServerUpgradeStateMachine")
|
||||
|
||||
|
||||
case .modifying:
|
||||
fatalError("Internal inconsistency in HTTPServerUpgradeStateMachine")
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
enum UpgradingHandlerCompletedAction {
|
||||
case fireErrorCaughtAndStartUnbuffering(Error)
|
||||
case removeHandler(UpgradeResult)
|
||||
case fireErrorCaughtAndRemoveHandler(Error)
|
||||
case startUnbuffering(UpgradeResult)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
mutating func upgradingHandlerCompleted(_ result: Result<UpgradeResult, Error>) -> UpgradingHandlerCompletedAction? {
|
||||
switch self.state {
|
||||
case .initial:
|
||||
fatalError("Internal inconsistency in HTTPServerUpgradeStateMachine")
|
||||
|
||||
case .upgrading(let upgrading):
|
||||
switch result {
|
||||
case .success(let value):
|
||||
if !upgrading.buffer.isEmpty {
|
||||
self.state = .unbuffering(.init(buffer: upgrading.buffer))
|
||||
return .startUnbuffering(value)
|
||||
} else {
|
||||
self.state = .finished
|
||||
return .removeHandler(value)
|
||||
}
|
||||
|
||||
case .failure(let error):
|
||||
if !upgrading.buffer.isEmpty {
|
||||
// So we failed to upgrade. There is nothing really that we can do here.
|
||||
// We are unbuffering the reads but there shouldn't be any handler in the pipeline
|
||||
// that expects a specific type of reads anyhow.
|
||||
self.state = .unbuffering(.init(buffer: upgrading.buffer))
|
||||
return .fireErrorCaughtAndStartUnbuffering(error)
|
||||
} else {
|
||||
self.state = .finished
|
||||
return .fireErrorCaughtAndRemoveHandler(error)
|
||||
}
|
||||
}
|
||||
|
||||
case .finished:
|
||||
// We have to tolerate this
|
||||
return nil
|
||||
|
||||
case .awaitingUpgrader, .upgraderReady, .unbuffering:
|
||||
fatalError("Internal inconsistency in HTTPServerUpgradeStateMachine")
|
||||
|
||||
case .modifying:
|
||||
fatalError("Internal inconsistency in HTTPServerUpgradeStateMachine")
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
enum FindingUpgraderCompletedAction {
|
||||
case startUpgrading(upgrader: any NIOTypedHTTPServerProtocolUpgrader<UpgradeResult>, responseHeaders: HTTPHeaders, proto: String)
|
||||
case runNotUpgradingInitializer
|
||||
case fireErrorCaughtAndStartUnbuffering(Error)
|
||||
case fireErrorCaughtAndRemoveHandler(Error)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
mutating func findingUpgraderCompleted(
|
||||
requestHead: HTTPRequestHead,
|
||||
_ result: Result<(upgrader: any NIOTypedHTTPServerProtocolUpgrader<UpgradeResult>, responseHeaders: HTTPHeaders, proto: String)?, Error>
|
||||
) -> FindingUpgraderCompletedAction? {
|
||||
switch self.state {
|
||||
case .initial, .upgraderReady:
|
||||
fatalError("Internal inconsistency in HTTPServerUpgradeStateMachine")
|
||||
|
||||
case .awaitingUpgrader(let awaitingUpgrader):
|
||||
switch result {
|
||||
case .success(.some((let upgrader, let responseHeaders, let proto))):
|
||||
if awaitingUpgrader.seenFirstRequest {
|
||||
// We have seen the end of the request. So we can upgrade now.
|
||||
self.state = .upgrading(.init(buffer: awaitingUpgrader.buffer))
|
||||
return .startUpgrading(upgrader: upgrader, responseHeaders: responseHeaders, proto: proto)
|
||||
} else {
|
||||
// We have not yet seen the end so we have to wait until that happens
|
||||
self.state = .upgraderReady(.init(
|
||||
upgrader: upgrader,
|
||||
requestHead: requestHead,
|
||||
responseHeaders: responseHeaders,
|
||||
proto: proto,
|
||||
buffer: awaitingUpgrader.buffer
|
||||
))
|
||||
return nil
|
||||
}
|
||||
|
||||
case .success(.none):
|
||||
// There was no upgrader to handle the request. We just run the not upgrading
|
||||
// initializer now.
|
||||
self.state = .upgrading(.init(buffer: awaitingUpgrader.buffer))
|
||||
return .runNotUpgradingInitializer
|
||||
|
||||
case .failure(let error):
|
||||
if !awaitingUpgrader.buffer.isEmpty {
|
||||
self.state = .unbuffering(.init(buffer: awaitingUpgrader.buffer))
|
||||
return .fireErrorCaughtAndStartUnbuffering(error)
|
||||
} else {
|
||||
self.state = .finished
|
||||
return .fireErrorCaughtAndRemoveHandler(error)
|
||||
}
|
||||
}
|
||||
|
||||
case .upgrading, .unbuffering, .finished:
|
||||
fatalError("Internal inconsistency in HTTPServerUpgradeStateMachine")
|
||||
|
||||
case .modifying:
|
||||
fatalError("Internal inconsistency in HTTPServerUpgradeStateMachine")
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
enum UnbufferAction {
|
||||
case fireChannelRead(NIOAny)
|
||||
case fireChannelReadCompleteAndRemoveHandler
|
||||
}
|
||||
|
||||
@inlinable
|
||||
mutating func unbuffer() -> UnbufferAction {
|
||||
switch self.state {
|
||||
case .initial, .awaitingUpgrader, .upgraderReady, .upgrading, .finished:
|
||||
preconditionFailure("Invalid state \(self.state)")
|
||||
|
||||
case .unbuffering(var unbuffering):
|
||||
self.state = .modifying
|
||||
|
||||
if let element = unbuffering.buffer.popFirst() {
|
||||
self.state = .unbuffering(unbuffering)
|
||||
|
||||
return .fireChannelRead(element)
|
||||
} else {
|
||||
self.state = .finished
|
||||
|
||||
return .fireChannelReadCompleteAndRemoveHandler
|
||||
}
|
||||
|
||||
case .modifying:
|
||||
fatalError("Internal inconsistency in HTTPServerUpgradeStateMachine")
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -13,8 +13,8 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import CNIOSHA1
|
||||
import NIOCore
|
||||
import NIOHTTP1
|
||||
@_spi(AsyncChannel) import NIOCore
|
||||
@_spi(AsyncChannel) import NIOHTTP1
|
||||
|
||||
let magicWebSocketGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
|
||||
|
||||
@@ -156,28 +156,136 @@ public final class NIOWebSocketServerUpgrader: HTTPServerProtocolUpgrader, @unch
|
||||
}
|
||||
|
||||
public func buildUpgradeResponse(channel: Channel, upgradeRequest: HTTPRequestHead, initialResponseHeaders: HTTPHeaders) -> EventLoopFuture<HTTPHeaders> {
|
||||
let key: String
|
||||
let version: String
|
||||
return _buildUpgradeResponse(
|
||||
channel: channel,
|
||||
upgradeRequest: upgradeRequest,
|
||||
initialResponseHeaders: initialResponseHeaders,
|
||||
shouldUpgrade: self.shouldUpgrade
|
||||
)
|
||||
}
|
||||
|
||||
do {
|
||||
key = try upgradeRequest.headers.nonListHeader("Sec-WebSocket-Key")
|
||||
version = try upgradeRequest.headers.nonListHeader("Sec-WebSocket-Version")
|
||||
} catch {
|
||||
return channel.eventLoop.makeFailedFuture(error)
|
||||
}
|
||||
public func upgrade(context: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture<Void> {
|
||||
_upgrade(
|
||||
channel: context.channel,
|
||||
upgradeRequest: upgradeRequest,
|
||||
maxFrameSize: self.maxFrameSize,
|
||||
automaticErrorHandling: self.automaticErrorHandling,
|
||||
upgradePipelineHandler: self.upgradePipelineHandler
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// The version must be 13.
|
||||
guard version == "13" else {
|
||||
return channel.eventLoop.makeFailedFuture(NIOWebSocketUpgradeError.invalidUpgradeHeader)
|
||||
}
|
||||
/// A `NIOTypedHTTPServerProtocolUpgrader` that knows how to do the WebSocket upgrade dance.
|
||||
///
|
||||
/// Users may frequently want to offer multiple websocket endpoints on the same port. For this
|
||||
/// reason, this `WebServerSocketUpgrader` only knows how to do the required parts of the upgrade and to
|
||||
/// complete the handshake. Users are expected to provide a callback that examines the HTTP headers
|
||||
/// (including the path) and determines whether this is a websocket upgrade request that is acceptable
|
||||
/// to them.
|
||||
///
|
||||
/// This upgrader assumes that the `HTTPServerUpgradeHandler` will appropriately mutate the pipeline to
|
||||
/// remove the HTTP `ChannelHandler`s.
|
||||
@_spi(AsyncChannel)
|
||||
public final class NIOTypedWebSocketServerUpgrader<UpgradeResult: Sendable>: NIOTypedHTTPServerProtocolUpgrader, Sendable {
|
||||
private typealias ShouldUpgrade = @Sendable (Channel, HTTPRequestHead) -> EventLoopFuture<HTTPHeaders?>
|
||||
private typealias UpgradePipelineHandler = @Sendable (Channel, HTTPRequestHead) -> EventLoopFuture<UpgradeResult>
|
||||
|
||||
return self.shouldUpgrade(channel, upgradeRequest).flatMapThrowing { extraHeaders in
|
||||
guard let extraHeaders = extraHeaders else {
|
||||
/// RFC 6455 specs this as the required entry in the Upgrade header.
|
||||
public let supportedProtocol: String = "websocket"
|
||||
|
||||
/// We deliberately do not actually set any required headers here, because the websocket
|
||||
/// spec annoyingly does not actually force the client to send these in the Upgrade header,
|
||||
/// which NIO requires. We check for these manually.
|
||||
public let requiredUpgradeHeaders: [String] = []
|
||||
|
||||
private let shouldUpgrade: ShouldUpgrade
|
||||
private let upgradePipelineHandler: UpgradePipelineHandler
|
||||
private let maxFrameSize: Int
|
||||
private let enableAutomaticErrorHandling: Bool
|
||||
|
||||
/// Create a new ``NIOTypedWebSocketServerUpgrader``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - maxFrameSize: The maximum frame size the decoder is willing to tolerate from the
|
||||
/// remote peer. WebSockets in principle allows frame sizes up to `2**64` bytes, but
|
||||
/// this is an objectively unreasonable maximum value (on AMD64 systems it is not
|
||||
/// possible to even. Users may set this to any value up to `UInt32.max`.
|
||||
/// - automaticErrorHandling: Whether the pipeline should automatically handle protocol
|
||||
/// errors by sending error responses and closing the connection. Defaults to `true`,
|
||||
/// may be set to `false` if the user wishes to handle their own errors.
|
||||
/// - shouldUpgrade: A callback that determines whether the websocket request should be
|
||||
/// upgraded. This callback is responsible for creating a `HTTPHeaders` object with
|
||||
/// any headers that it needs on the response *except for* the `Upgrade`, `Connection`,
|
||||
/// and `Sec-WebSocket-Accept` headers, which this upgrader will handle. Should return
|
||||
/// an `EventLoopFuture` containing `nil` if the upgrade should be refused.
|
||||
/// - enableAutomaticErrorHandling: A function that will be called once the upgrade response is
|
||||
/// flushed, and that is expected to mutate the `Channel` appropriately to handle the
|
||||
/// websocket protocol. This only needs to add the user handlers: the
|
||||
/// `WebSocketFrameEncoder` and `WebSocketFrameDecoder` will have been added to the
|
||||
/// pipeline automatically.
|
||||
public init(
|
||||
maxFrameSize: Int = 1 << 14,
|
||||
enableAutomaticErrorHandling: Bool = true,
|
||||
shouldUpgrade: @escaping @Sendable (Channel, HTTPRequestHead) -> EventLoopFuture<HTTPHeaders?>,
|
||||
upgradePipelineHandler: @escaping @Sendable (Channel, HTTPRequestHead) -> EventLoopFuture<UpgradeResult>
|
||||
) {
|
||||
precondition(maxFrameSize <= UInt32.max, "invalid overlarge max frame size")
|
||||
self.shouldUpgrade = shouldUpgrade
|
||||
self.upgradePipelineHandler = upgradePipelineHandler
|
||||
self.maxFrameSize = maxFrameSize
|
||||
self.enableAutomaticErrorHandling = enableAutomaticErrorHandling
|
||||
}
|
||||
|
||||
public func buildUpgradeResponse(
|
||||
channel: Channel,
|
||||
upgradeRequest: HTTPRequestHead,
|
||||
initialResponseHeaders: HTTPHeaders
|
||||
) -> EventLoopFuture<HTTPHeaders> {
|
||||
_buildUpgradeResponse(
|
||||
channel: channel,
|
||||
upgradeRequest: upgradeRequest,
|
||||
initialResponseHeaders: initialResponseHeaders,
|
||||
shouldUpgrade: self.shouldUpgrade
|
||||
)
|
||||
}
|
||||
|
||||
public func upgrade(channel: Channel, upgradeRequest: HTTPRequestHead) -> EventLoopFuture<UpgradeResult> {
|
||||
_upgrade(
|
||||
channel: channel,
|
||||
upgradeRequest: upgradeRequest,
|
||||
maxFrameSize: self.maxFrameSize,
|
||||
automaticErrorHandling: self.enableAutomaticErrorHandling,
|
||||
upgradePipelineHandler: self.upgradePipelineHandler
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private func _buildUpgradeResponse(
|
||||
channel: Channel,
|
||||
upgradeRequest: HTTPRequestHead,
|
||||
initialResponseHeaders: HTTPHeaders,
|
||||
shouldUpgrade: @Sendable (Channel, HTTPRequestHead) -> EventLoopFuture<HTTPHeaders?>
|
||||
) -> EventLoopFuture<HTTPHeaders> {
|
||||
let key: String
|
||||
let version: String
|
||||
|
||||
do {
|
||||
key = try upgradeRequest.headers.nonListHeader("Sec-WebSocket-Key")
|
||||
version = try upgradeRequest.headers.nonListHeader("Sec-WebSocket-Version")
|
||||
} catch {
|
||||
return channel.eventLoop.makeFailedFuture(error)
|
||||
}
|
||||
|
||||
// The version must be 13.
|
||||
guard version == "13" else {
|
||||
return channel.eventLoop.makeFailedFuture(NIOWebSocketUpgradeError.invalidUpgradeHeader)
|
||||
}
|
||||
|
||||
return shouldUpgrade(channel, upgradeRequest)
|
||||
.flatMapThrowing { extraHeaders in
|
||||
guard var extraHeaders = extraHeaders else {
|
||||
throw NIOWebSocketUpgradeError.unsupportedWebSocketTarget
|
||||
}
|
||||
return extraHeaders
|
||||
}.map { (extraHeaders: HTTPHeaders) in
|
||||
var extraHeaders = extraHeaders
|
||||
|
||||
// Cool, we're good to go! Let's do our upgrade. We do this by concatenating the magic
|
||||
// GUID to the base64-encoded key and taking a SHA1 hash of the result.
|
||||
@@ -195,23 +303,27 @@ public final class NIOWebSocketServerUpgrader: HTTPServerProtocolUpgrader, @unch
|
||||
|
||||
return extraHeaders
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func upgrade(context: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture<Void> {
|
||||
/// We never use the automatic error handling feature of the WebSocketFrameDecoder: we always use the separate channel
|
||||
/// handler.
|
||||
var upgradeFuture = context.pipeline.addHandler(WebSocketFrameEncoder()).flatMap {
|
||||
context.pipeline.addHandler(ByteToMessageHandler(WebSocketFrameDecoder(maxFrameSize: self.maxFrameSize)))
|
||||
}
|
||||
private func _upgrade<UpgradeResult>(
|
||||
channel: Channel,
|
||||
upgradeRequest: HTTPRequestHead,
|
||||
maxFrameSize: Int,
|
||||
automaticErrorHandling: Bool,
|
||||
upgradePipelineHandler: @escaping @Sendable (Channel, HTTPRequestHead) -> EventLoopFuture<UpgradeResult>
|
||||
) -> EventLoopFuture<UpgradeResult> {
|
||||
/// We never use the automatic error handling feature of the WebSocketFrameDecoder: we always use the separate channel
|
||||
/// handler.
|
||||
channel.eventLoop.makeCompletedFuture {
|
||||
try channel.pipeline.syncOperations.addHandler(WebSocketFrameEncoder())
|
||||
try channel.pipeline.syncOperations.addHandler(
|
||||
ByteToMessageHandler(WebSocketFrameDecoder(maxFrameSize: maxFrameSize))
|
||||
)
|
||||
|
||||
if self.automaticErrorHandling {
|
||||
upgradeFuture = upgradeFuture.flatMap {
|
||||
context.pipeline.addHandler(WebSocketProtocolErrorHandler())
|
||||
}
|
||||
}
|
||||
|
||||
return upgradeFuture.flatMap {
|
||||
self.upgradePipelineHandler(context.channel, upgradeRequest)
|
||||
if automaticErrorHandling {
|
||||
try channel.pipeline.syncOperations.addHandler(WebSocketProtocolErrorHandler())
|
||||
}
|
||||
}.flatMap {
|
||||
upgradePipelineHandler(channel, upgradeRequest)
|
||||
}
|
||||
}
|
||||
@@ -146,7 +146,7 @@ private final class WebSocketPingPongHandler: ChannelInboundHandler {
|
||||
private func pingTestFrameData(context: ChannelHandlerContext) {
|
||||
let buffer = context.channel.allocator.buffer(string: self.testFrameData)
|
||||
let frame = WebSocketFrame(fin: true, opcode: .ping, data: buffer)
|
||||
context.write(self.wrapOutboundOut(frame), promise: nil)
|
||||
context.writeAndFlush(self.wrapOutboundOut(frame), promise: nil)
|
||||
}
|
||||
|
||||
private func pong(context: ChannelHandlerContext, frame: WebSocketFrame) {
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if swift(>=5.9)
|
||||
@_spi(AsyncChannel) import NIOCore
|
||||
@_spi(AsyncChannel) import NIOPosix
|
||||
@_spi(AsyncChannel) import NIOHTTP1
|
||||
@_spi(AsyncChannel) import NIOWebSocket
|
||||
|
||||
let websocketResponse = """
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Swift NIO WebSocket Test Page</title>
|
||||
<script>
|
||||
var wsconnection = new WebSocket("ws://localhost:8888/websocket");
|
||||
wsconnection.onmessage = function (msg) {
|
||||
var element = document.createElement("p");
|
||||
element.innerHTML = msg.data;
|
||||
|
||||
var textDiv = document.getElementById("websocket-stream");
|
||||
textDiv.insertBefore(element, null);
|
||||
};
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<h1>WebSocket Stream</h1>
|
||||
<div id="websocket-stream"></div>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
|
||||
@available(macOS 14, *)
|
||||
@main
|
||||
struct Server {
|
||||
/// The server's host.
|
||||
private let host: String
|
||||
/// The server's port.
|
||||
private let port: Int
|
||||
/// The server's event loop group.
|
||||
private let eventLoopGroup: MultiThreadedEventLoopGroup
|
||||
|
||||
private static let responseBody = ByteBuffer(string: websocketResponse)
|
||||
|
||||
enum UpgradeResult {
|
||||
case websocket(NIOAsyncChannel<WebSocketFrame, WebSocketFrame>)
|
||||
case notUpgraded(NIOAsyncChannel<HTTPServerRequestPart, HTTPPart<HTTPResponseHead, ByteBuffer>>)
|
||||
}
|
||||
|
||||
static func main() async throws {
|
||||
let server = Server(
|
||||
host: "localhost",
|
||||
port: 8888,
|
||||
eventLoopGroup: .singleton
|
||||
)
|
||||
try await server.run()
|
||||
}
|
||||
|
||||
/// This method starts the server and handles incoming connections.
|
||||
func run() async throws {
|
||||
let channel: NIOAsyncChannel<EventLoopFuture<UpgradeResult>, Never> = try await ServerBootstrap(group: self.eventLoopGroup)
|
||||
.serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
|
||||
.bind(
|
||||
host: self.host,
|
||||
port: self.port
|
||||
) { channel in
|
||||
channel.eventLoop.makeCompletedFuture {
|
||||
let upgrader = NIOTypedWebSocketServerUpgrader<UpgradeResult>(
|
||||
shouldUpgrade: { (channel, head) in
|
||||
channel.eventLoop.makeSucceededFuture(HTTPHeaders())
|
||||
},
|
||||
upgradePipelineHandler: { (channel, _) in
|
||||
channel.eventLoop.makeCompletedFuture {
|
||||
let asyncChannel = try NIOAsyncChannel<WebSocketFrame, WebSocketFrame>(synchronouslyWrapping: channel)
|
||||
return UpgradeResult.websocket(asyncChannel)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
let serverUpgradeConfiguration = NIOTypedHTTPServerUpgradeConfiguration(
|
||||
upgraders: [upgrader],
|
||||
notUpgradingCompletionHandler: { channel in
|
||||
channel.eventLoop.makeCompletedFuture {
|
||||
try channel.pipeline.syncOperations.addHandler(HTTPByteBufferResponsePartHandler())
|
||||
let asyncChannel = try NIOAsyncChannel<HTTPServerRequestPart, HTTPPart<HTTPResponseHead, ByteBuffer>>(synchronouslyWrapping: channel)
|
||||
return UpgradeResult.notUpgraded(asyncChannel)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
let negotiationResultFuture = try channel.pipeline.syncOperations.configureUpgradableHTTPServerPipeline(
|
||||
configuration: .init(upgradeConfiguration: serverUpgradeConfiguration)
|
||||
)
|
||||
|
||||
return negotiationResultFuture
|
||||
}
|
||||
}
|
||||
|
||||
// We are handling each incoming connection in a separate child task. It is important
|
||||
// to use a discarding task group here which automatically discards finished child tasks.
|
||||
// A normal task group retains all child tasks and their outputs in memory until they are
|
||||
// consumed by iterating the group or by exiting the group. Since, we are never consuming
|
||||
// the results of the group we need the group to automatically discard them; otherwise, this
|
||||
// would result in a memory leak over time.
|
||||
try await withThrowingDiscardingTaskGroup { group in
|
||||
for try await upgradeResult in channel.inboundStream {
|
||||
group.addTask {
|
||||
await self.handleUpgradeResult(upgradeResult)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// This method handles a single connection by echoing back all inbound data.
|
||||
private func handleUpgradeResult(_ upgradeResult: EventLoopFuture<UpgradeResult>) async {
|
||||
// Note that this method is non-throwing and we are catching any error.
|
||||
// We do this since we don't want to tear down the whole server when a single connection
|
||||
// encounters an error.
|
||||
do {
|
||||
switch try await upgradeResult.get() {
|
||||
case .websocket(let websocketChannel):
|
||||
print("Handling websocket connection")
|
||||
try await self.handleWebsocketChannel(websocketChannel)
|
||||
print("Done handling websocket connection")
|
||||
case .notUpgraded(let httpChannel):
|
||||
print("Handling HTTP connection")
|
||||
try await self.handleHTTPChannel(httpChannel)
|
||||
print("Done handling HTTP connection")
|
||||
}
|
||||
} catch {
|
||||
print("Hit error: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
private func handleWebsocketChannel(_ channel: NIOAsyncChannel<WebSocketFrame, WebSocketFrame>) async throws {
|
||||
try await withThrowingTaskGroup(of: Void.self) { group in
|
||||
group.addTask {
|
||||
for try await frame in channel.inboundStream {
|
||||
switch frame.opcode {
|
||||
case .ping:
|
||||
print("Received ping")
|
||||
var frameData = frame.data
|
||||
let maskingKey = frame.maskKey
|
||||
|
||||
if let maskingKey = maskingKey {
|
||||
frameData.webSocketUnmask(maskingKey)
|
||||
}
|
||||
|
||||
let responseFrame = WebSocketFrame(fin: true, opcode: .pong, data: frameData)
|
||||
try await channel.outboundWriter.write(responseFrame)
|
||||
|
||||
case .connectionClose:
|
||||
// This is an unsolicited close. We're going to send a response frame and
|
||||
// then, when we've sent it, close up shop. We should send back the close code the remote
|
||||
// peer sent us, unless they didn't send one at all.
|
||||
print("Received close")
|
||||
var data = frame.unmaskedData
|
||||
let closeDataCode = data.readSlice(length: 2) ?? ByteBuffer()
|
||||
let closeFrame = WebSocketFrame(fin: true, opcode: .connectionClose, data: closeDataCode)
|
||||
try await channel.outboundWriter.write(closeFrame)
|
||||
return
|
||||
case .binary, .continuation, .pong:
|
||||
// We ignore these frames.
|
||||
break
|
||||
default:
|
||||
// Unknown frames are errors.
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
group.addTask {
|
||||
// This is our main business logic where we are just sending the current time
|
||||
// every second.
|
||||
while true {
|
||||
// We can't really check for error here, but it's also not the purpose of the
|
||||
// example so let's not worry about it.
|
||||
let theTime = ContinuousClock().now
|
||||
var buffer = channel.channel.allocator.buffer(capacity: 12)
|
||||
buffer.writeString("\(theTime)")
|
||||
|
||||
let frame = WebSocketFrame(fin: true, opcode: .text, data: buffer)
|
||||
|
||||
print("Sending time")
|
||||
try await channel.outboundWriter.write(frame)
|
||||
try await Task.sleep(for: .seconds(1))
|
||||
}
|
||||
}
|
||||
|
||||
try await group.next()
|
||||
group.cancelAll()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private func handleHTTPChannel(_ channel: NIOAsyncChannel<HTTPServerRequestPart, HTTPPart<HTTPResponseHead, ByteBuffer>>) async throws {
|
||||
for try await requestPart in channel.inboundStream {
|
||||
// We're not interested in request bodies here: we're just serving up GET responses
|
||||
// to get the client to initiate a websocket request.
|
||||
guard case .head(let head) = requestPart else {
|
||||
return
|
||||
}
|
||||
|
||||
// GETs only.
|
||||
guard case .GET = head.method else {
|
||||
try await self.respond405(writer: channel.outboundWriter)
|
||||
return
|
||||
}
|
||||
|
||||
var headers = HTTPHeaders()
|
||||
headers.add(name: "Content-Type", value: "text/html")
|
||||
headers.add(name: "Content-Length", value: String(Self.responseBody.readableBytes))
|
||||
headers.add(name: "Connection", value: "close")
|
||||
let responseHead = HTTPResponseHead(
|
||||
version: .init(major: 1, minor: 1),
|
||||
status: .ok,
|
||||
headers: headers
|
||||
)
|
||||
|
||||
try await channel.outboundWriter.write(
|
||||
contentsOf: [
|
||||
.head(responseHead),
|
||||
.body(Self.responseBody),
|
||||
.end(nil)
|
||||
]
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private func respond405(writer: NIOAsyncChannelOutboundWriter<HTTPPart<HTTPResponseHead, ByteBuffer>>) async throws {
|
||||
var headers = HTTPHeaders()
|
||||
headers.add(name: "Connection", value: "close")
|
||||
headers.add(name: "Content-Length", value: "0")
|
||||
let head = HTTPResponseHead(
|
||||
version: .http1_1,
|
||||
status: .methodNotAllowed,
|
||||
headers: headers
|
||||
)
|
||||
|
||||
try await writer.write(
|
||||
contentsOf: [
|
||||
.head(head),
|
||||
.end(nil)
|
||||
]
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
final class HTTPByteBufferResponsePartHandler: ChannelOutboundHandler {
|
||||
typealias OutboundIn = HTTPPart<HTTPResponseHead, ByteBuffer>
|
||||
typealias OutboundOut = HTTPServerResponsePart
|
||||
|
||||
func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
|
||||
let part = self.unwrapOutboundIn(data)
|
||||
switch part {
|
||||
case .head(let head):
|
||||
context.write(self.wrapOutboundOut(.head(head)), promise: promise)
|
||||
case .body(let buffer):
|
||||
context.write(self.wrapOutboundOut(.body(.byteBuffer(buffer))), promise: promise)
|
||||
case .end(let trailers):
|
||||
context.write(self.wrapOutboundOut(.end(trailers)), promise: promise)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#else
|
||||
@main
|
||||
struct Server {
|
||||
static func main() {
|
||||
fatalError("Requires at least Swift 5.9")
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,282 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2017-2021 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 NIOPosix
|
||||
import NIOHTTP1
|
||||
import NIOWebSocket
|
||||
|
||||
let websocketResponse = """
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Swift NIO WebSocket Test Page</title>
|
||||
<script>
|
||||
var wsconnection = new WebSocket("ws://localhost:8888/websocket");
|
||||
wsconnection.onmessage = function (msg) {
|
||||
var element = document.createElement("p");
|
||||
element.innerHTML = msg.data;
|
||||
|
||||
var textDiv = document.getElementById("websocket-stream");
|
||||
textDiv.insertBefore(element, null);
|
||||
};
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<h1>WebSocket Stream</h1>
|
||||
<div id="websocket-stream"></div>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
|
||||
private final class HTTPHandler: ChannelInboundHandler, RemovableChannelHandler {
|
||||
typealias InboundIn = HTTPServerRequestPart
|
||||
typealias OutboundOut = HTTPServerResponsePart
|
||||
|
||||
private var responseBody: ByteBuffer!
|
||||
|
||||
func handlerAdded(context: ChannelHandlerContext) {
|
||||
self.responseBody = context.channel.allocator.buffer(string: websocketResponse)
|
||||
}
|
||||
|
||||
func handlerRemoved(context: ChannelHandlerContext) {
|
||||
self.responseBody = nil
|
||||
}
|
||||
|
||||
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
|
||||
let reqPart = self.unwrapInboundIn(data)
|
||||
|
||||
// We're not interested in request bodies here: we're just serving up GET responses
|
||||
// to get the client to initiate a websocket request.
|
||||
guard case .head(let head) = reqPart else {
|
||||
return
|
||||
}
|
||||
|
||||
// GETs only.
|
||||
guard case .GET = head.method else {
|
||||
self.respond405(context: context)
|
||||
return
|
||||
}
|
||||
|
||||
var headers = HTTPHeaders()
|
||||
headers.add(name: "Content-Type", value: "text/html")
|
||||
headers.add(name: "Content-Length", value: String(self.responseBody.readableBytes))
|
||||
headers.add(name: "Connection", value: "close")
|
||||
let responseHead = HTTPResponseHead(version: .init(major: 1, minor: 1),
|
||||
status: .ok,
|
||||
headers: headers)
|
||||
context.write(self.wrapOutboundOut(.head(responseHead)), promise: nil)
|
||||
context.write(self.wrapOutboundOut(.body(.byteBuffer(self.responseBody))), promise: nil)
|
||||
context.write(self.wrapOutboundOut(.end(nil))).whenComplete { (_: Result<Void, Error>) in
|
||||
context.close(promise: nil)
|
||||
}
|
||||
context.flush()
|
||||
}
|
||||
|
||||
private func respond405(context: ChannelHandlerContext) {
|
||||
var headers = HTTPHeaders()
|
||||
headers.add(name: "Connection", value: "close")
|
||||
headers.add(name: "Content-Length", value: "0")
|
||||
let head = HTTPResponseHead(version: .http1_1,
|
||||
status: .methodNotAllowed,
|
||||
headers: headers)
|
||||
context.write(self.wrapOutboundOut(.head(head)), promise: nil)
|
||||
context.write(self.wrapOutboundOut(.end(nil))).whenComplete { (_: Result<Void, Error>) in
|
||||
context.close(promise: nil)
|
||||
}
|
||||
context.flush()
|
||||
}
|
||||
}
|
||||
|
||||
private final class WebSocketTimeHandler: ChannelInboundHandler {
|
||||
typealias InboundIn = WebSocketFrame
|
||||
typealias OutboundOut = WebSocketFrame
|
||||
|
||||
private var awaitingClose: Bool = false
|
||||
|
||||
public func handlerAdded(context: ChannelHandlerContext) {
|
||||
self.sendTime(context: context)
|
||||
}
|
||||
|
||||
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
|
||||
let frame = self.unwrapInboundIn(data)
|
||||
|
||||
switch frame.opcode {
|
||||
case .connectionClose:
|
||||
self.receivedClose(context: context, frame: frame)
|
||||
case .ping:
|
||||
self.pong(context: context, frame: frame)
|
||||
case .text:
|
||||
var data = frame.unmaskedData
|
||||
let text = data.readString(length: data.readableBytes) ?? ""
|
||||
print(text)
|
||||
case .binary, .continuation, .pong:
|
||||
// We ignore these frames.
|
||||
break
|
||||
default:
|
||||
// Unknown frames are errors.
|
||||
self.closeOnError(context: context)
|
||||
}
|
||||
}
|
||||
|
||||
public func channelReadComplete(context: ChannelHandlerContext) {
|
||||
context.flush()
|
||||
}
|
||||
|
||||
private func sendTime(context: ChannelHandlerContext) {
|
||||
guard context.channel.isActive else { return }
|
||||
|
||||
// We can't send if we sent a close message.
|
||||
guard !self.awaitingClose else { return }
|
||||
|
||||
// We can't really check for error here, but it's also not the purpose of the
|
||||
// example so let's not worry about it.
|
||||
let theTime = NIODeadline.now().uptimeNanoseconds
|
||||
var buffer = context.channel.allocator.buffer(capacity: 12)
|
||||
buffer.writeString("\(theTime)")
|
||||
|
||||
let frame = WebSocketFrame(fin: true, opcode: .text, data: buffer)
|
||||
context.writeAndFlush(self.wrapOutboundOut(frame)).map {
|
||||
context.eventLoop.scheduleTask(in: .seconds(1), { self.sendTime(context: context) })
|
||||
}.whenFailure { (_: Error) in
|
||||
context.close(promise: nil)
|
||||
}
|
||||
}
|
||||
|
||||
private func receivedClose(context: ChannelHandlerContext, frame: WebSocketFrame) {
|
||||
// Handle a received close frame. In websockets, we're just going to send the close
|
||||
// frame and then close, unless we already sent our own close frame.
|
||||
if awaitingClose {
|
||||
// Cool, we started the close and were waiting for the user. We're done.
|
||||
context.close(promise: nil)
|
||||
} else {
|
||||
// This is an unsolicited close. We're going to send a response frame and
|
||||
// then, when we've sent it, close up shop. We should send back the close code the remote
|
||||
// peer sent us, unless they didn't send one at all.
|
||||
var data = frame.unmaskedData
|
||||
let closeDataCode = data.readSlice(length: 2) ?? ByteBuffer()
|
||||
let closeFrame = WebSocketFrame(fin: true, opcode: .connectionClose, data: closeDataCode)
|
||||
_ = context.write(self.wrapOutboundOut(closeFrame)).map { () in
|
||||
context.close(promise: nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func pong(context: ChannelHandlerContext, frame: WebSocketFrame) {
|
||||
var frameData = frame.data
|
||||
let maskingKey = frame.maskKey
|
||||
|
||||
if let maskingKey = maskingKey {
|
||||
frameData.webSocketUnmask(maskingKey)
|
||||
}
|
||||
|
||||
let responseFrame = WebSocketFrame(fin: true, opcode: .pong, data: frameData)
|
||||
context.write(self.wrapOutboundOut(responseFrame), promise: nil)
|
||||
}
|
||||
|
||||
private func closeOnError(context: ChannelHandlerContext) {
|
||||
// We have hit an error, we want to close. We do that by sending a close frame and then
|
||||
// shutting down the write side of the connection.
|
||||
var data = context.channel.allocator.buffer(capacity: 2)
|
||||
data.write(webSocketErrorCode: .protocolError)
|
||||
let frame = WebSocketFrame(fin: true, opcode: .connectionClose, data: data)
|
||||
context.write(self.wrapOutboundOut(frame)).whenComplete { (_: Result<Void, Error>) in
|
||||
context.close(mode: .output, promise: nil)
|
||||
}
|
||||
awaitingClose = true
|
||||
}
|
||||
}
|
||||
|
||||
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
|
||||
|
||||
let upgrader = NIOWebSocketServerUpgrader(shouldUpgrade: { (channel: Channel, head: HTTPRequestHead) in channel.eventLoop.makeSucceededFuture(HTTPHeaders()) },
|
||||
upgradePipelineHandler: { (channel: Channel, _: HTTPRequestHead) in
|
||||
channel.pipeline.addHandler(WebSocketTimeHandler())
|
||||
})
|
||||
|
||||
let bootstrap = ServerBootstrap(group: group)
|
||||
// Specify backlog and enable SO_REUSEADDR for the server itself
|
||||
.serverChannelOption(ChannelOptions.backlog, value: 256)
|
||||
.serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
|
||||
|
||||
// Set the handlers that are applied to the accepted Channels
|
||||
.childChannelInitializer { channel in
|
||||
let httpHandler = HTTPHandler()
|
||||
let config: NIOHTTPServerUpgradeConfiguration = (
|
||||
upgraders: [ upgrader ],
|
||||
completionHandler: { _ in
|
||||
channel.pipeline.removeHandler(httpHandler, promise: nil)
|
||||
}
|
||||
)
|
||||
return channel.pipeline.configureHTTPServerPipeline(withServerUpgrade: config).flatMap {
|
||||
channel.pipeline.addHandler(httpHandler)
|
||||
}
|
||||
}
|
||||
|
||||
// Enable SO_REUSEADDR for the accepted Channels
|
||||
.childChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
|
||||
|
||||
defer {
|
||||
try! group.syncShutdownGracefully()
|
||||
}
|
||||
|
||||
// First argument is the program path
|
||||
let arguments = CommandLine.arguments
|
||||
let arg1 = arguments.dropFirst().first
|
||||
let arg2 = arguments.dropFirst(2).first
|
||||
|
||||
let defaultHost = "localhost"
|
||||
let defaultPort = 8888
|
||||
|
||||
enum BindTo {
|
||||
case ip(host: String, port: Int)
|
||||
case unixDomainSocket(path: String)
|
||||
}
|
||||
|
||||
let bindTarget: BindTo
|
||||
switch (arg1, arg1.flatMap(Int.init), arg2.flatMap(Int.init)) {
|
||||
case (.some(let h), _ , .some(let p)):
|
||||
/* we got two arguments, let's interpret that as host and port */
|
||||
bindTarget = .ip(host: h, port: p)
|
||||
|
||||
case (let portString?, .none, _):
|
||||
// Couldn't parse as number, expecting unix domain socket path.
|
||||
bindTarget = .unixDomainSocket(path: portString)
|
||||
|
||||
case (_, let p?, _):
|
||||
// Only one argument --> port.
|
||||
bindTarget = .ip(host: defaultHost, port: p)
|
||||
|
||||
default:
|
||||
bindTarget = .ip(host: defaultHost, port: defaultPort)
|
||||
}
|
||||
|
||||
let channel = try { () -> Channel in
|
||||
switch bindTarget {
|
||||
case .ip(let host, let port):
|
||||
return try bootstrap.bind(host: host, port: port).wait()
|
||||
case .unixDomainSocket(let path):
|
||||
return try bootstrap.bind(unixDomainSocketPath: path).wait()
|
||||
}
|
||||
}()
|
||||
|
||||
guard let localAddress = channel.localAddress else {
|
||||
fatalError("Address was unable to bind. Please check that the socket was not closed or that the address family was understood.")
|
||||
}
|
||||
print("Server started and listening on \(localAddress)")
|
||||
|
||||
// This will never unblock as we don't close the ServerChannel
|
||||
try channel.closeFuture.wait()
|
||||
|
||||
print("Server closed")
|
||||
@@ -13,11 +13,10 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import Dispatch
|
||||
import NIOCore
|
||||
import NIOEmbedded
|
||||
@testable import NIOPosix
|
||||
@testable import NIOHTTP1
|
||||
@testable @_spi(AsyncChannel) import NIOHTTP1
|
||||
|
||||
extension ChannelPipeline {
|
||||
fileprivate func assertDoesNotContainUpgrader() throws {
|
||||
@@ -36,7 +35,11 @@ extension ChannelPipeline {
|
||||
}
|
||||
|
||||
fileprivate func assertContainsUpgrader() throws {
|
||||
try self.assertContains(handlerType: HTTPServerUpgradeHandler.self)
|
||||
do {
|
||||
_ = try self.context(handlerType: NIOTypedHTTPServerUpgradeHandler<Bool>.self).wait()
|
||||
} catch {
|
||||
try self.assertContains(handlerType: HTTPServerUpgradeHandler.self)
|
||||
}
|
||||
}
|
||||
|
||||
func assertContains<Handler: ChannelHandler>(handlerType: Handler.Type) throws {
|
||||
@@ -87,7 +90,7 @@ private typealias UpgradeCompletionHandler = @Sendable (ChannelHandlerContext) -
|
||||
|
||||
private func serverHTTPChannelWithAutoremoval(group: EventLoopGroup,
|
||||
pipelining: Bool,
|
||||
upgraders: [HTTPServerProtocolUpgrader],
|
||||
upgraders: [any TypedAndUntypedHTTPServerProtocolUpgrader],
|
||||
extraHandlers: [ChannelHandler],
|
||||
_ upgradeCompletionHandler: @escaping UpgradeCompletionHandler) throws -> (Channel, EventLoopFuture<Channel>) {
|
||||
let p = group.next().makePromise(of: Channel.self)
|
||||
@@ -137,20 +140,6 @@ private func connectedClientChannel(group: EventLoopGroup, serverAddress: Socket
|
||||
.wait()
|
||||
}
|
||||
|
||||
private func setUpTestWithAutoremoval(pipelining: Bool = false,
|
||||
upgraders: [HTTPServerProtocolUpgrader],
|
||||
extraHandlers: [ChannelHandler],
|
||||
_ upgradeCompletionHandler: @escaping UpgradeCompletionHandler) throws -> (EventLoopGroup, Channel, Channel, Channel) {
|
||||
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
|
||||
let (serverChannel, connectedServerChannelFuture) = try serverHTTPChannelWithAutoremoval(group: group,
|
||||
pipelining: pipelining,
|
||||
upgraders: upgraders,
|
||||
extraHandlers: extraHandlers,
|
||||
upgradeCompletionHandler)
|
||||
let clientChannel = try connectedClientChannel(group: group, serverAddress: serverChannel.localAddress!)
|
||||
return (group, serverChannel, clientChannel, try connectedServerChannelFuture.wait())
|
||||
}
|
||||
|
||||
internal func assertResponseIs(response: String, expectedResponseLine: String, expectedResponseHeaders: [String]) {
|
||||
var lines = response.split(separator: "\r\n", omittingEmptySubsequences: false).map { String($0) }
|
||||
|
||||
@@ -175,7 +164,9 @@ internal func assertResponseIs(response: String, expectedResponseLine: String, e
|
||||
XCTAssertEqual(lines.count, 0)
|
||||
}
|
||||
|
||||
private class ExplodingUpgrader: HTTPServerProtocolUpgrader {
|
||||
protocol TypedAndUntypedHTTPServerProtocolUpgrader: HTTPServerProtocolUpgrader, NIOTypedHTTPServerProtocolUpgrader where UpgradeResult == Bool {}
|
||||
|
||||
private class ExplodingUpgrader: TypedAndUntypedHTTPServerProtocolUpgrader {
|
||||
let supportedProtocol: String
|
||||
let requiredUpgradeHeaders: [String]
|
||||
|
||||
@@ -197,9 +188,14 @@ private class ExplodingUpgrader: HTTPServerProtocolUpgrader {
|
||||
XCTFail("upgrade called")
|
||||
return context.eventLoop.makeSucceededFuture(())
|
||||
}
|
||||
|
||||
func upgrade(channel: Channel, upgradeRequest: HTTPRequestHead) -> EventLoopFuture<Bool> {
|
||||
XCTFail("upgrade called")
|
||||
return channel.eventLoop.makeSucceededFuture(true)
|
||||
}
|
||||
}
|
||||
|
||||
private class UpgraderSaysNo: HTTPServerProtocolUpgrader {
|
||||
private class UpgraderSaysNo: TypedAndUntypedHTTPServerProtocolUpgrader {
|
||||
let supportedProtocol: String
|
||||
let requiredUpgradeHeaders: [String] = []
|
||||
|
||||
@@ -219,9 +215,14 @@ private class UpgraderSaysNo: HTTPServerProtocolUpgrader {
|
||||
XCTFail("upgrade called")
|
||||
return context.eventLoop.makeSucceededFuture(())
|
||||
}
|
||||
|
||||
func upgrade(channel: Channel, upgradeRequest: HTTPRequestHead) -> EventLoopFuture<Bool> {
|
||||
XCTFail("upgrade called")
|
||||
return channel.eventLoop.makeSucceededFuture(true)
|
||||
}
|
||||
}
|
||||
|
||||
private class SuccessfulUpgrader: HTTPServerProtocolUpgrader {
|
||||
private class SuccessfulUpgrader: TypedAndUntypedHTTPServerProtocolUpgrader {
|
||||
let supportedProtocol: String
|
||||
let requiredUpgradeHeaders: [String]
|
||||
private let onUpgradeComplete: (HTTPRequestHead) -> ()
|
||||
@@ -256,13 +257,18 @@ private class SuccessfulUpgrader: HTTPServerProtocolUpgrader {
|
||||
self.onUpgradeComplete(upgradeRequest)
|
||||
return context.eventLoop.makeSucceededFuture(())
|
||||
}
|
||||
|
||||
func upgrade(channel: Channel, upgradeRequest: HTTPRequestHead) -> EventLoopFuture<Bool> {
|
||||
self.onUpgradeComplete(upgradeRequest)
|
||||
return channel.eventLoop.makeSucceededFuture(true)
|
||||
}
|
||||
}
|
||||
|
||||
private class DelayedUnsuccessfulUpgrader: HTTPServerProtocolUpgrader {
|
||||
private class DelayedUnsuccessfulUpgrader: TypedAndUntypedHTTPServerProtocolUpgrader {
|
||||
let supportedProtocol: String
|
||||
let requiredUpgradeHeaders: [String]
|
||||
|
||||
private var upgradePromise: EventLoopPromise<Void>?
|
||||
private var upgradePromise: EventLoopPromise<Bool>?
|
||||
|
||||
init(forProtocol `protocol`: String) {
|
||||
self.supportedProtocol = `protocol`
|
||||
@@ -277,19 +283,24 @@ private class DelayedUnsuccessfulUpgrader: HTTPServerProtocolUpgrader {
|
||||
|
||||
func upgrade(context: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture<Void> {
|
||||
self.upgradePromise = context.eventLoop.makePromise()
|
||||
return self.upgradePromise!.futureResult
|
||||
return self.upgradePromise!.futureResult.map { _ in }
|
||||
}
|
||||
|
||||
func unblockUpgrade(withError error: Error) {
|
||||
self.upgradePromise!.fail(error)
|
||||
}
|
||||
|
||||
func upgrade(channel: Channel, upgradeRequest: HTTPRequestHead) -> EventLoopFuture<Bool> {
|
||||
self.upgradePromise = channel.eventLoop.makePromise(of: Bool.self)
|
||||
return self.upgradePromise!.futureResult
|
||||
}
|
||||
}
|
||||
|
||||
private class UpgradeDelayer: HTTPServerProtocolUpgrader {
|
||||
private class UpgradeDelayer: TypedAndUntypedHTTPServerProtocolUpgrader {
|
||||
let supportedProtocol: String
|
||||
let requiredUpgradeHeaders: [String] = []
|
||||
|
||||
private var upgradePromise: EventLoopPromise<Void>?
|
||||
private var upgradePromise: EventLoopPromise<Bool>?
|
||||
|
||||
public init(forProtocol `protocol`: String) {
|
||||
self.supportedProtocol = `protocol`
|
||||
@@ -303,11 +314,16 @@ private class UpgradeDelayer: HTTPServerProtocolUpgrader {
|
||||
|
||||
public func upgrade(context: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture<Void> {
|
||||
self.upgradePromise = context.eventLoop.makePromise()
|
||||
return self.upgradePromise!.futureResult
|
||||
return self.upgradePromise!.futureResult.map { _ in }
|
||||
}
|
||||
|
||||
public func unblockUpgrade() {
|
||||
self.upgradePromise!.succeed(())
|
||||
self.upgradePromise!.succeed(true)
|
||||
}
|
||||
|
||||
func upgrade(channel: Channel, upgradeRequest: HTTPRequestHead) -> EventLoopFuture<Bool> {
|
||||
self.upgradePromise = channel.eventLoop.makePromise(of: Bool.self)
|
||||
return self.upgradePromise!.futureResult
|
||||
}
|
||||
}
|
||||
|
||||
@@ -392,6 +408,21 @@ private class ReentrantReadOnChannelReadCompleteHandler: ChannelInboundHandler {
|
||||
}
|
||||
|
||||
class HTTPServerUpgradeTestCase: XCTestCase {
|
||||
fileprivate func setUpTestWithAutoremoval(pipelining: Bool = false,
|
||||
upgraders: [any TypedAndUntypedHTTPServerProtocolUpgrader],
|
||||
extraHandlers: [ChannelHandler],
|
||||
notUpgradingHandler: (@Sendable (Channel) -> EventLoopFuture<Bool>)? = nil,
|
||||
_ upgradeCompletionHandler: @escaping UpgradeCompletionHandler) throws -> (EventLoopGroup, Channel, Channel, Channel) {
|
||||
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
|
||||
let (serverChannel, connectedServerChannelFuture) = try serverHTTPChannelWithAutoremoval(group: group,
|
||||
pipelining: pipelining,
|
||||
upgraders: upgraders,
|
||||
extraHandlers: extraHandlers,
|
||||
upgradeCompletionHandler)
|
||||
let clientChannel = try connectedClientChannel(group: group, serverAddress: serverChannel.localAddress!)
|
||||
return (group, serverChannel, clientChannel, try connectedServerChannelFuture.wait())
|
||||
}
|
||||
|
||||
func testUpgradeWithoutUpgrade() throws {
|
||||
let (group, server, client, connectedServer) = try setUpTestWithAutoremoval(upgraders: [ExplodingUpgrader(forProtocol: "myproto")],
|
||||
extraHandlers: []) { (_: ChannelHandlerContext) in
|
||||
@@ -758,14 +789,9 @@ class HTTPServerUpgradeTestCase: XCTestCase {
|
||||
}
|
||||
|
||||
func testDelayedUpgradeBehaviour() throws {
|
||||
let g = DispatchGroup()
|
||||
g.enter()
|
||||
|
||||
let upgrader = UpgradeDelayer(forProtocol: "myproto")
|
||||
let (group, server, client, connectedServer) = try setUpTestWithAutoremoval(upgraders: [upgrader],
|
||||
extraHandlers: []) { context in
|
||||
g.leave()
|
||||
}
|
||||
extraHandlers: []) { context in }
|
||||
defer {
|
||||
XCTAssertNoThrow(try group.syncShutdownGracefully())
|
||||
}
|
||||
@@ -784,8 +810,6 @@ class HTTPServerUpgradeTestCase: XCTestCase {
|
||||
let request = "OPTIONS * HTTP/1.1\r\nHost: localhost\r\nUpgrade: myproto\r\nConnection: upgrade\r\n\r\n"
|
||||
XCTAssertNoThrow(try client.writeAndFlush(NIOAny(client.allocator.buffer(string: request))).wait())
|
||||
|
||||
g.wait()
|
||||
|
||||
// Ok, we don't think this upgrade should have succeeded yet, but neither should it have failed. We want to
|
||||
// dispatch onto the server event loop and check that the channel still contains the upgrade handler.
|
||||
try connectedServer.pipeline.assertContainsUpgrader()
|
||||
@@ -800,16 +824,11 @@ class HTTPServerUpgradeTestCase: XCTestCase {
|
||||
}
|
||||
|
||||
func testBuffersInboundDataDuringDelayedUpgrade() throws {
|
||||
let g = DispatchGroup()
|
||||
g.enter()
|
||||
|
||||
let upgrader = UpgradeDelayer(forProtocol: "myproto")
|
||||
let dataRecorder = DataRecorder<ByteBuffer>()
|
||||
|
||||
let (group, server, client, _) = try setUpTestWithAutoremoval(upgraders: [upgrader],
|
||||
extraHandlers: [dataRecorder]) { context in
|
||||
g.leave()
|
||||
}
|
||||
extraHandlers: [dataRecorder]) { context in }
|
||||
defer {
|
||||
XCTAssertNoThrow(try group.syncShutdownGracefully())
|
||||
}
|
||||
@@ -824,14 +843,10 @@ class HTTPServerUpgradeTestCase: XCTestCase {
|
||||
}
|
||||
XCTAssertNoThrow(try client.pipeline.addHandler(clientHandler).wait())
|
||||
|
||||
// This request is safe to upgrade, but is immediately followed by non-HTTP data that will probably
|
||||
// blow up the HTTP parser.
|
||||
// This request is safe to upgrade, but is immediately followed by non-HTTP data.
|
||||
let request = "OPTIONS * HTTP/1.1\r\nHost: localhost\r\nUpgrade: myproto\r\nConnection: upgrade\r\n\r\n"
|
||||
XCTAssertNoThrow(try client.writeAndFlush(NIOAny(client.allocator.buffer(string: request))).wait())
|
||||
|
||||
// Wait for the upgrade machinery to run.
|
||||
g.wait()
|
||||
|
||||
// Ok, send the application data in.
|
||||
let appData = "supersecretawesome data definitely not http\r\nawesome\r\ndata\ryeah"
|
||||
XCTAssertNoThrow(try client.writeAndFlush(NIOAny(client.allocator.buffer(string: appData))).wait())
|
||||
@@ -1538,3 +1553,517 @@ class HTTPServerUpgradeTestCase: XCTestCase {
|
||||
try channel.pipeline.assertContainsUpgrader()
|
||||
}
|
||||
}
|
||||
|
||||
final class TypedHTTPServerUpgradeTestCase: HTTPServerUpgradeTestCase {
|
||||
fileprivate override func setUpTestWithAutoremoval(
|
||||
pipelining: Bool = false,
|
||||
upgraders: [any TypedAndUntypedHTTPServerProtocolUpgrader],
|
||||
extraHandlers: [ChannelHandler],
|
||||
notUpgradingHandler: (@Sendable (Channel) -> EventLoopFuture<Bool>)? = nil,
|
||||
_ upgradeCompletionHandler: @escaping UpgradeCompletionHandler
|
||||
) throws -> (EventLoopGroup, Channel, Channel, Channel) {
|
||||
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
|
||||
let connectionChannelPromise = group.next().makePromise(of: Channel.self)
|
||||
let serverChannelFuture = ServerBootstrap(group: group)
|
||||
.serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
|
||||
.childChannelInitializer { channel in
|
||||
channel.eventLoop.makeCompletedFuture {
|
||||
connectionChannelPromise.succeed(channel)
|
||||
var configuration = NIOUpgradableHTTPServerPipelineConfiguration(
|
||||
upgradeConfiguration: .init(
|
||||
upgraders: upgraders.map { $0 as! any NIOTypedHTTPServerProtocolUpgrader<Bool> },
|
||||
notUpgradingCompletionHandler: { notUpgradingHandler?($0) ?? $0.eventLoop.makeSucceededFuture(false) }
|
||||
)
|
||||
)
|
||||
configuration.enablePipelining = pipelining
|
||||
return try channel.pipeline.syncOperations.configureUpgradableHTTPServerPipeline(configuration: configuration)
|
||||
.flatMap { result in
|
||||
if result {
|
||||
return channel.pipeline.context(handlerType: NIOTypedHTTPServerUpgradeHandler<Bool>.self)
|
||||
.map {
|
||||
upgradeCompletionHandler($0)
|
||||
}
|
||||
} else {
|
||||
return channel.eventLoop.makeSucceededVoidFuture()
|
||||
}
|
||||
}
|
||||
}
|
||||
.flatMap { _ in
|
||||
let futureResults = extraHandlers.map { channel.pipeline.addHandler($0) }
|
||||
return EventLoopFuture.andAllSucceed(futureResults, on: channel.eventLoop)
|
||||
}
|
||||
}.bind(host: "127.0.0.1", port: 0)
|
||||
let clientChannel = try connectedClientChannel(group: group, serverAddress: serverChannelFuture.wait().localAddress!)
|
||||
return (group, try serverChannelFuture.wait(), clientChannel, try connectionChannelPromise.futureResult.wait())
|
||||
}
|
||||
|
||||
func testNotUpgrading() throws {
|
||||
let notUpgraderCbFired = UnsafeMutableTransferBox(false)
|
||||
|
||||
let upgrader = SuccessfulUpgrader(forProtocol: "myproto", requiringHeaders: ["kafkaesque"]) { _ in }
|
||||
|
||||
let (group, _, client, connectedServer) = try setUpTestWithAutoremoval(
|
||||
upgraders: [upgrader],
|
||||
extraHandlers: [],
|
||||
notUpgradingHandler: { channel in
|
||||
notUpgraderCbFired.wrappedValue = true
|
||||
// We're closing the connection now.
|
||||
channel.close(promise: nil)
|
||||
return channel.eventLoop.makeSucceededFuture(true)
|
||||
}
|
||||
) { _ in }
|
||||
defer {
|
||||
XCTAssertNoThrow(try group.syncShutdownGracefully())
|
||||
}
|
||||
|
||||
let completePromise = group.next().makePromise(of: Void.self)
|
||||
let clientHandler = ArrayAccumulationHandler<ByteBuffer> { buffers in
|
||||
let resultString = buffers.map { $0.getString(at: $0.readerIndex, length: $0.readableBytes)! }.joined(separator: "")
|
||||
XCTAssertEqual(resultString, "")
|
||||
completePromise.succeed(())
|
||||
}
|
||||
XCTAssertNoThrow(try client.pipeline.addHandler(clientHandler).wait())
|
||||
|
||||
// This request is safe to upgrade.
|
||||
let request = "OPTIONS * HTTP/1.1\r\nHost: localhost\r\nUpgrade: notmyproto\r\nKafkaesque: yup\r\nConnection: upgrade\r\nConnection: kafkaesque\r\n\r\n"
|
||||
XCTAssertNoThrow(try client.writeAndFlush(NIOAny(client.allocator.buffer(string: request))).wait())
|
||||
|
||||
// Let the machinery do its thing.
|
||||
XCTAssertNoThrow(try completePromise.futureResult.wait())
|
||||
|
||||
// At this time we want to assert that the not upgrader got called.
|
||||
XCTAssert(notUpgraderCbFired.wrappedValue)
|
||||
|
||||
// We also want to confirm that the upgrade handler is no longer in the pipeline.
|
||||
try connectedServer.pipeline.assertDoesNotContainUpgrader()
|
||||
}
|
||||
|
||||
// - MARK: The following tests are all overridden from the base class since they slightly differ in behaviour
|
||||
|
||||
override func testSimpleUpgradeSucceeds() throws {
|
||||
// This test is different since we call the completionHandler after the upgrader
|
||||
// modified the pipeline in the typed version.
|
||||
let upgradeRequest = UnsafeMutableTransferBox<HTTPRequestHead?>(nil)
|
||||
let upgradeHandlerCbFired = UnsafeMutableTransferBox(false)
|
||||
let upgraderCbFired = UnsafeMutableTransferBox(false)
|
||||
|
||||
let upgrader = SuccessfulUpgrader(forProtocol: "myproto", requiringHeaders: ["kafkaesque"]) { req in
|
||||
// This is called before completion block.
|
||||
upgradeRequest.wrappedValue = req
|
||||
upgradeHandlerCbFired.wrappedValue = true
|
||||
|
||||
XCTAssert(upgradeHandlerCbFired.wrappedValue)
|
||||
upgraderCbFired.wrappedValue = true
|
||||
}
|
||||
|
||||
let (group, _, client, connectedServer) = try setUpTestWithAutoremoval(
|
||||
upgraders: [upgrader],
|
||||
extraHandlers: []
|
||||
) { (context) in
|
||||
// This is called before the upgrader gets called.
|
||||
XCTAssertNotNil(upgradeRequest.wrappedValue)
|
||||
upgradeHandlerCbFired.wrappedValue = true
|
||||
|
||||
// We're closing the connection now.
|
||||
context.close(promise: nil)
|
||||
}
|
||||
defer {
|
||||
XCTAssertNoThrow(try group.syncShutdownGracefully())
|
||||
}
|
||||
|
||||
let completePromise = group.next().makePromise(of: Void.self)
|
||||
let clientHandler = ArrayAccumulationHandler<ByteBuffer> { buffers in
|
||||
let resultString = buffers.map { $0.getString(at: $0.readerIndex, length: $0.readableBytes)! }.joined(separator: "")
|
||||
assertResponseIs(response: resultString,
|
||||
expectedResponseLine: "HTTP/1.1 101 Switching Protocols",
|
||||
expectedResponseHeaders: ["X-Upgrade-Complete: true", "upgrade: myproto", "connection: upgrade"])
|
||||
completePromise.succeed(())
|
||||
}
|
||||
XCTAssertNoThrow(try client.pipeline.addHandler(clientHandler).wait())
|
||||
|
||||
// This request is safe to upgrade.
|
||||
let request = "OPTIONS * HTTP/1.1\r\nHost: localhost\r\nUpgrade: myproto\r\nKafkaesque: yup\r\nConnection: upgrade\r\nConnection: kafkaesque\r\n\r\n"
|
||||
XCTAssertNoThrow(try client.writeAndFlush(NIOAny(client.allocator.buffer(string: request))).wait())
|
||||
|
||||
// Let the machinery do its thing.
|
||||
XCTAssertNoThrow(try completePromise.futureResult.wait())
|
||||
|
||||
// At this time we want to assert that everything got called. Their own callbacks assert
|
||||
// that the ordering was correct.
|
||||
XCTAssert(upgradeHandlerCbFired.wrappedValue)
|
||||
XCTAssert(upgraderCbFired.wrappedValue)
|
||||
|
||||
// We also want to confirm that the upgrade handler is no longer in the pipeline.
|
||||
try connectedServer.pipeline.assertDoesNotContainUpgrader()
|
||||
}
|
||||
|
||||
override func testUpgradeRespectsClientPreference() throws {
|
||||
// This test is different since we call the completionHandler after the upgrader
|
||||
// modified the pipeline in the typed version.
|
||||
let upgradeRequest = UnsafeMutableTransferBox<HTTPRequestHead?>(nil)
|
||||
let upgradeHandlerCbFired = UnsafeMutableTransferBox(false)
|
||||
let upgraderCbFired = UnsafeMutableTransferBox(false)
|
||||
|
||||
let explodingUpgrader = ExplodingUpgrader(forProtocol: "exploder")
|
||||
let successfulUpgrader = SuccessfulUpgrader(forProtocol: "myproto", requiringHeaders: ["kafkaesque"]) { req in
|
||||
upgradeRequest.wrappedValue = req
|
||||
XCTAssertFalse(upgradeHandlerCbFired.wrappedValue)
|
||||
upgraderCbFired.wrappedValue = true
|
||||
}
|
||||
|
||||
let (group, _, client, connectedServer) = try setUpTestWithAutoremoval(upgraders: [explodingUpgrader, successfulUpgrader],
|
||||
extraHandlers: []) { context in
|
||||
// This is called before the upgrader gets called.
|
||||
XCTAssertNotNil(upgradeRequest.wrappedValue)
|
||||
upgradeHandlerCbFired.wrappedValue = true
|
||||
|
||||
// We're closing the connection now.
|
||||
context.close(promise: nil)
|
||||
}
|
||||
defer {
|
||||
XCTAssertNoThrow(try group.syncShutdownGracefully())
|
||||
}
|
||||
|
||||
let completePromise = group.next().makePromise(of: Void.self)
|
||||
let clientHandler = ArrayAccumulationHandler<ByteBuffer> { buffers in
|
||||
let resultString = buffers.map { $0.getString(at: $0.readerIndex, length: $0.readableBytes)! }.joined(separator: "")
|
||||
assertResponseIs(response: resultString,
|
||||
expectedResponseLine: "HTTP/1.1 101 Switching Protocols",
|
||||
expectedResponseHeaders: ["X-Upgrade-Complete: true", "upgrade: myproto", "connection: upgrade"])
|
||||
completePromise.succeed(())
|
||||
}
|
||||
XCTAssertNoThrow(try client.pipeline.addHandler(clientHandler).wait())
|
||||
|
||||
// This request is safe to upgrade.
|
||||
let request = "OPTIONS * HTTP/1.1\r\nHost: localhost\r\nUpgrade: myproto, exploder\r\nKafkaesque: yup\r\nConnection: upgrade, kafkaesque\r\n\r\n"
|
||||
XCTAssertNoThrow(try client.writeAndFlush(NIOAny(client.allocator.buffer(string: request))).wait())
|
||||
|
||||
// Let the machinery do its thing.
|
||||
XCTAssertNoThrow(try completePromise.futureResult.wait())
|
||||
|
||||
// At this time we want to assert that everything got called. Their own callbacks assert
|
||||
// that the ordering was correct.
|
||||
XCTAssert(upgradeHandlerCbFired.wrappedValue)
|
||||
XCTAssert(upgraderCbFired.wrappedValue)
|
||||
|
||||
// We also want to confirm that the upgrade handler is no longer in the pipeline.
|
||||
try connectedServer.pipeline.waitForUpgraderToBeRemoved()
|
||||
}
|
||||
|
||||
override func testUpgraderCanRejectUpgradeForPersonalReasons() throws {
|
||||
// This test is different since we call the completionHandler after the upgrader
|
||||
// modified the pipeline in the typed version.
|
||||
let upgradeRequest = UnsafeMutableTransferBox<HTTPRequestHead?>(nil)
|
||||
let upgradeHandlerCbFired = UnsafeMutableTransferBox(false)
|
||||
let upgraderCbFired = UnsafeMutableTransferBox(false)
|
||||
|
||||
let explodingUpgrader = UpgraderSaysNo(forProtocol: "noproto")
|
||||
let successfulUpgrader = SuccessfulUpgrader(forProtocol: "myproto", requiringHeaders: ["kafkaesque"]) { req in
|
||||
upgradeRequest.wrappedValue = req
|
||||
XCTAssertFalse(upgradeHandlerCbFired.wrappedValue)
|
||||
upgraderCbFired.wrappedValue = true
|
||||
}
|
||||
let errorCatcher = ErrorSaver()
|
||||
|
||||
let (group, _, client, connectedServer) = try setUpTestWithAutoremoval(upgraders: [explodingUpgrader, successfulUpgrader],
|
||||
extraHandlers: [errorCatcher]) { context in
|
||||
// This is called before the upgrader gets called.
|
||||
XCTAssertNotNil(upgradeRequest.wrappedValue)
|
||||
upgradeHandlerCbFired.wrappedValue = true
|
||||
|
||||
// We're closing the connection now.
|
||||
context.close(promise: nil)
|
||||
}
|
||||
defer {
|
||||
XCTAssertNoThrow(try group.syncShutdownGracefully())
|
||||
}
|
||||
|
||||
let completePromise = group.next().makePromise(of: Void.self)
|
||||
let clientHandler = ArrayAccumulationHandler<ByteBuffer> { buffers in
|
||||
let resultString = buffers.map { $0.getString(at: $0.readerIndex, length: $0.readableBytes)! }.joined(separator: "")
|
||||
assertResponseIs(response: resultString,
|
||||
expectedResponseLine: "HTTP/1.1 101 Switching Protocols",
|
||||
expectedResponseHeaders: ["X-Upgrade-Complete: true", "upgrade: myproto", "connection: upgrade"])
|
||||
completePromise.succeed(())
|
||||
}
|
||||
XCTAssertNoThrow(try client.pipeline.addHandler(clientHandler).wait())
|
||||
|
||||
// This request is safe to upgrade.
|
||||
let request = "OPTIONS * HTTP/1.1\r\nHost: localhost\r\nUpgrade: noproto,myproto\r\nKafkaesque: yup\r\nConnection: upgrade, kafkaesque\r\n\r\n"
|
||||
XCTAssertNoThrow(try client.writeAndFlush(NIOAny(client.allocator.buffer(string: request))).wait())
|
||||
|
||||
// Let the machinery do its thing.
|
||||
XCTAssertNoThrow(try completePromise.futureResult.wait())
|
||||
|
||||
// At this time we want to assert that everything got called. Their own callbacks assert
|
||||
// that the ordering was correct.
|
||||
XCTAssert(upgradeHandlerCbFired.wrappedValue)
|
||||
XCTAssert(upgraderCbFired.wrappedValue)
|
||||
|
||||
// We also want to confirm that the upgrade handler is no longer in the pipeline.
|
||||
try connectedServer.pipeline.waitForUpgraderToBeRemoved()
|
||||
|
||||
// And we want to confirm we saved the error.
|
||||
XCTAssertEqual(errorCatcher.errors.count, 1)
|
||||
|
||||
switch(errorCatcher.errors[0]) {
|
||||
case UpgraderSaysNo.No.no:
|
||||
break
|
||||
default:
|
||||
XCTFail("Unexpected error: \(errorCatcher.errors[0])")
|
||||
}
|
||||
}
|
||||
|
||||
override func testUpgradeWithUpgradePayloadInlineWithRequestWorks() throws {
|
||||
// This test is different since we call the completionHandler after the upgrader
|
||||
// modified the pipeline in the typed version.
|
||||
enum ReceivedTheWrongThingError: Error { case error }
|
||||
let upgradeRequest = UnsafeMutableTransferBox<HTTPRequestHead?>(nil)
|
||||
let upgradeHandlerCbFired = UnsafeMutableTransferBox(false)
|
||||
let upgraderCbFired = UnsafeMutableTransferBox(false)
|
||||
|
||||
class CheckWeReadInlineAndExtraData: ChannelDuplexHandler {
|
||||
typealias InboundIn = ByteBuffer
|
||||
typealias OutboundIn = Never
|
||||
typealias OutboundOut = Never
|
||||
|
||||
enum State {
|
||||
case fresh
|
||||
case added
|
||||
case inlineDataRead
|
||||
case extraDataRead
|
||||
case closed
|
||||
}
|
||||
|
||||
private let firstByteDonePromise: EventLoopPromise<Void>
|
||||
private let secondByteDonePromise: EventLoopPromise<Void>
|
||||
private let allDonePromise: EventLoopPromise<Void>
|
||||
private var state = State.fresh
|
||||
|
||||
init(firstByteDonePromise: EventLoopPromise<Void>,
|
||||
secondByteDonePromise: EventLoopPromise<Void>,
|
||||
allDonePromise: EventLoopPromise<Void>) {
|
||||
self.firstByteDonePromise = firstByteDonePromise
|
||||
self.secondByteDonePromise = secondByteDonePromise
|
||||
self.allDonePromise = allDonePromise
|
||||
}
|
||||
|
||||
func handlerAdded(context: ChannelHandlerContext) {
|
||||
XCTAssertEqual(.fresh, self.state)
|
||||
self.state = .added
|
||||
}
|
||||
|
||||
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
|
||||
var buf = self.unwrapInboundIn(data)
|
||||
XCTAssertEqual(1, buf.readableBytes)
|
||||
let stringRead = buf.readString(length: buf.readableBytes)
|
||||
switch self.state {
|
||||
case .added:
|
||||
XCTAssertEqual("A", stringRead)
|
||||
self.state = .inlineDataRead
|
||||
if stringRead == .some("A") {
|
||||
self.firstByteDonePromise.succeed(())
|
||||
} else {
|
||||
self.firstByteDonePromise.fail(ReceivedTheWrongThingError.error)
|
||||
}
|
||||
case .inlineDataRead:
|
||||
XCTAssertEqual("B", stringRead)
|
||||
self.state = .extraDataRead
|
||||
context.channel.close(promise: nil)
|
||||
if stringRead == .some("B") {
|
||||
self.secondByteDonePromise.succeed(())
|
||||
} else {
|
||||
self.secondByteDonePromise.fail(ReceivedTheWrongThingError.error)
|
||||
}
|
||||
default:
|
||||
XCTFail("channel read in wrong state \(self.state)")
|
||||
}
|
||||
}
|
||||
|
||||
func close(context: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise<Void>?) {
|
||||
XCTAssertEqual(.extraDataRead, self.state)
|
||||
self.state = .closed
|
||||
context.close(mode: mode, promise: promise)
|
||||
|
||||
self.allDonePromise.succeed(())
|
||||
}
|
||||
}
|
||||
|
||||
let upgrader = SuccessfulUpgrader(forProtocol: "myproto", requiringHeaders: ["kafkaesque"]) { req in
|
||||
upgradeRequest.wrappedValue = req
|
||||
XCTAssertFalse(upgradeHandlerCbFired.wrappedValue)
|
||||
upgraderCbFired.wrappedValue = true
|
||||
}
|
||||
|
||||
let promiseGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
|
||||
defer {
|
||||
XCTAssertNoThrow(try promiseGroup.syncShutdownGracefully())
|
||||
}
|
||||
let firstByteDonePromise = promiseGroup.next().makePromise(of: Void.self)
|
||||
let secondByteDonePromise = promiseGroup.next().makePromise(of: Void.self)
|
||||
let allDonePromise = promiseGroup.next().makePromise(of: Void.self)
|
||||
let (group, _, client, connectedServer) = try setUpTestWithAutoremoval(upgraders: [upgrader],
|
||||
extraHandlers: []) { (context) in
|
||||
// This is called before the upgrader gets called.
|
||||
XCTAssertNotNil(upgradeRequest.wrappedValue)
|
||||
upgradeHandlerCbFired.wrappedValue = true
|
||||
|
||||
_ = context.channel.pipeline.addHandler(CheckWeReadInlineAndExtraData(firstByteDonePromise: firstByteDonePromise,
|
||||
secondByteDonePromise: secondByteDonePromise,
|
||||
allDonePromise: allDonePromise))
|
||||
}
|
||||
defer {
|
||||
XCTAssertNoThrow(try group.syncShutdownGracefully())
|
||||
}
|
||||
|
||||
let completePromise = group.next().makePromise(of: Void.self)
|
||||
let clientHandler = ArrayAccumulationHandler<ByteBuffer> { buffers in
|
||||
let resultString = buffers.map { $0.getString(at: $0.readerIndex, length: $0.readableBytes)! }.joined(separator: "")
|
||||
assertResponseIs(response: resultString,
|
||||
expectedResponseLine: "HTTP/1.1 101 Switching Protocols",
|
||||
expectedResponseHeaders: ["X-Upgrade-Complete: true", "upgrade: myproto", "connection: upgrade"])
|
||||
completePromise.succeed(())
|
||||
}
|
||||
XCTAssertNoThrow(try client.pipeline.addHandler(clientHandler).wait())
|
||||
|
||||
// This request is safe to upgrade.
|
||||
var request = "OPTIONS * HTTP/1.1\r\nHost: localhost\r\nUpgrade: myproto\r\nKafkaesque: yup\r\nConnection: upgrade\r\nConnection: kafkaesque\r\n\r\n"
|
||||
request += "A"
|
||||
XCTAssertNoThrow(try client.writeAndFlush(NIOAny(client.allocator.buffer(string: request))).wait())
|
||||
|
||||
XCTAssertNoThrow(try firstByteDonePromise.futureResult.wait() as Void)
|
||||
|
||||
XCTAssertNoThrow(try client.writeAndFlush(NIOAny(client.allocator.buffer(string: "B"))).wait())
|
||||
|
||||
XCTAssertNoThrow(try secondByteDonePromise.futureResult.wait() as Void)
|
||||
|
||||
XCTAssertNoThrow(try allDonePromise.futureResult.wait() as Void)
|
||||
|
||||
// Let the machinery do its thing.
|
||||
XCTAssertNoThrow(try completePromise.futureResult.wait())
|
||||
|
||||
// At this time we want to assert that everything got called. Their own callbacks assert
|
||||
// that the ordering was correct.
|
||||
XCTAssert(upgradeHandlerCbFired.wrappedValue)
|
||||
XCTAssert(upgraderCbFired.wrappedValue)
|
||||
|
||||
// We also want to confirm that the upgrade handler is no longer in the pipeline.
|
||||
try connectedServer.pipeline.assertDoesNotContainUpgrader()
|
||||
|
||||
XCTAssertNoThrow(try allDonePromise.futureResult.wait())
|
||||
}
|
||||
|
||||
override func testWeTolerateUpgradeFuturesFromWrongEventLoops() throws {
|
||||
// This test is different since we call the completionHandler after the upgrader
|
||||
// modified the pipeline in the typed version.
|
||||
let upgradeRequest = UnsafeMutableTransferBox<HTTPRequestHead?>(nil)
|
||||
let upgradeHandlerCbFired = UnsafeMutableTransferBox(false)
|
||||
let upgraderCbFired = UnsafeMutableTransferBox(false)
|
||||
let otherELG = MultiThreadedEventLoopGroup(numberOfThreads: 1)
|
||||
defer {
|
||||
XCTAssertNoThrow(try otherELG.syncShutdownGracefully())
|
||||
}
|
||||
|
||||
let upgrader = SuccessfulUpgrader(forProtocol: "myproto",
|
||||
requiringHeaders: ["kafkaesque"],
|
||||
buildUpgradeResponseFuture: {
|
||||
// this is the wrong EL
|
||||
otherELG.next().makeSucceededFuture($1)
|
||||
}) { req in
|
||||
upgradeRequest.wrappedValue = req
|
||||
XCTAssertFalse(upgradeHandlerCbFired.wrappedValue)
|
||||
upgraderCbFired.wrappedValue = true
|
||||
}
|
||||
|
||||
let (group, _, client, connectedServer) = try setUpTestWithAutoremoval(upgraders: [upgrader],
|
||||
extraHandlers: []) { (context) in
|
||||
// This is called before the upgrader gets called.
|
||||
XCTAssertNotNil(upgradeRequest.wrappedValue)
|
||||
upgradeHandlerCbFired.wrappedValue = true
|
||||
|
||||
// We're closing the connection now.
|
||||
context.close(promise: nil)
|
||||
}
|
||||
defer {
|
||||
XCTAssertNoThrow(try group.syncShutdownGracefully())
|
||||
}
|
||||
|
||||
let completePromise = group.next().makePromise(of: Void.self)
|
||||
let clientHandler = ArrayAccumulationHandler<ByteBuffer> { buffers in
|
||||
let resultString = buffers.map { $0.getString(at: $0.readerIndex, length: $0.readableBytes)! }.joined(separator: "")
|
||||
assertResponseIs(response: resultString,
|
||||
expectedResponseLine: "HTTP/1.1 101 Switching Protocols",
|
||||
expectedResponseHeaders: ["X-Upgrade-Complete: true", "upgrade: myproto", "connection: upgrade"])
|
||||
completePromise.succeed(())
|
||||
}
|
||||
XCTAssertNoThrow(try client.pipeline.addHandler(clientHandler).wait())
|
||||
|
||||
// This request is safe to upgrade.
|
||||
let request = "OPTIONS * HTTP/1.1\r\nHost: localhost\r\nUpgrade: myproto\r\nKafkaesque: yup\r\nConnection: upgrade\r\nConnection: kafkaesque\r\n\r\n"
|
||||
XCTAssertNoThrow(try client.writeAndFlush(NIOAny(client.allocator.buffer(string: request))).wait())
|
||||
|
||||
// Let the machinery do its thing.
|
||||
XCTAssertNoThrow(try completePromise.futureResult.wait())
|
||||
|
||||
// At this time we want to assert that everything got called. Their own callbacks assert
|
||||
// that the ordering was correct.
|
||||
XCTAssert(upgradeHandlerCbFired.wrappedValue)
|
||||
XCTAssert(upgraderCbFired.wrappedValue)
|
||||
|
||||
// We also want to confirm that the upgrade handler is no longer in the pipeline.
|
||||
try connectedServer.pipeline.assertDoesNotContainUpgrader()
|
||||
}
|
||||
|
||||
override func testUpgradeFiresUserEvent() throws {
|
||||
// This test is different since we call the completionHandler after the upgrader
|
||||
// modified the pipeline in the typed version.
|
||||
let eventSaver = UnsafeTransfer(UserEventSaver<HTTPServerUpgradeEvents>())
|
||||
|
||||
let upgrader = SuccessfulUpgrader(forProtocol: "myproto", requiringHeaders: []) { req in
|
||||
XCTAssertEqual(eventSaver.wrappedValue.events.count, 0)
|
||||
}
|
||||
|
||||
let (group, _, client, connectedServer) = try setUpTestWithAutoremoval(upgraders: [upgrader],
|
||||
extraHandlers: [eventSaver.wrappedValue]) { context in
|
||||
XCTAssertEqual(eventSaver.wrappedValue.events.count, 1)
|
||||
context.close(promise: nil)
|
||||
}
|
||||
defer {
|
||||
XCTAssertNoThrow(try group.syncShutdownGracefully())
|
||||
}
|
||||
|
||||
let completePromise = group.next().makePromise(of: Void.self)
|
||||
let clientHandler = ArrayAccumulationHandler<ByteBuffer> { buffers in
|
||||
let resultString = buffers.map { $0.getString(at: $0.readerIndex, length: $0.readableBytes)! }.joined(separator: "")
|
||||
assertResponseIs(response: resultString,
|
||||
expectedResponseLine: "HTTP/1.1 101 Switching Protocols",
|
||||
expectedResponseHeaders: ["X-Upgrade-Complete: true", "upgrade: myproto", "connection: upgrade"])
|
||||
completePromise.succeed(())
|
||||
}
|
||||
XCTAssertNoThrow(try client.pipeline.addHandler(clientHandler).wait())
|
||||
|
||||
// This request is safe to upgrade.
|
||||
let request = "OPTIONS * HTTP/1.1\r\nHost: localhost\r\nUpgrade: myproto\r\nKafkaesque: yup\r\nConnection: upgrade,kafkaesque\r\n\r\n"
|
||||
XCTAssertNoThrow(try client.writeAndFlush(NIOAny(client.allocator.buffer(string: request))).wait())
|
||||
|
||||
// Let the machinery do its thing.
|
||||
XCTAssertNoThrow(try completePromise.futureResult.wait())
|
||||
|
||||
// At this time we should have received one user event. We schedule this onto the
|
||||
// event loop to guarantee thread safety.
|
||||
XCTAssertNoThrow(try connectedServer.eventLoop.scheduleTask(deadline: .now()) {
|
||||
XCTAssertEqual(eventSaver.wrappedValue.events.count, 1)
|
||||
if case .upgradeComplete(let proto, let req) = eventSaver.wrappedValue.events[0] {
|
||||
XCTAssertEqual(proto, "myproto")
|
||||
XCTAssertEqual(req.method, .OPTIONS)
|
||||
XCTAssertEqual(req.uri, "*")
|
||||
XCTAssertEqual(req.version, .http1_1)
|
||||
} else {
|
||||
XCTFail("Unexpected event: \(eventSaver.wrappedValue.events[0])")
|
||||
}
|
||||
}.futureResult.wait())
|
||||
|
||||
// We also want to confirm that the upgrade handler is no longer in the pipeline.
|
||||
try connectedServer.pipeline.waitForUpgraderToBeRemoved()
|
||||
}
|
||||
}
|
||||
@@ -15,8 +15,8 @@
|
||||
import XCTest
|
||||
@testable import NIOCore
|
||||
import NIOEmbedded
|
||||
import NIOHTTP1
|
||||
@testable import NIOWebSocket
|
||||
@_spi(AsyncChannel) import NIOHTTP1
|
||||
@testable @_spi(AsyncChannel) import NIOWebSocket
|
||||
|
||||
extension EmbeddedChannel {
|
||||
func readAllInboundBuffers() throws -> ByteBuffer {
|
||||
@@ -112,10 +112,38 @@ private class WebSocketRecorderHandler: ChannelInboundHandler {
|
||||
}
|
||||
}
|
||||
|
||||
struct WebSocketServerUpgraderConfiguration {
|
||||
let maxFrameSize: Int
|
||||
let automaticErrorHandling: Bool
|
||||
let shouldUpgrade: @Sendable (Channel, HTTPRequestHead) -> EventLoopFuture<HTTPHeaders?>
|
||||
let upgradePipelineHandler: @Sendable (Channel, HTTPRequestHead) -> EventLoopFuture<Void>
|
||||
|
||||
@preconcurrency
|
||||
init(
|
||||
maxFrameSize: Int = 1 << 14,
|
||||
automaticErrorHandling: Bool = true,
|
||||
shouldUpgrade: @escaping @Sendable (Channel, HTTPRequestHead) -> EventLoopFuture<HTTPHeaders?>,
|
||||
upgradePipelineHandler: @escaping @Sendable (Channel, HTTPRequestHead) -> EventLoopFuture<Void>
|
||||
) {
|
||||
self.maxFrameSize = maxFrameSize
|
||||
self.automaticErrorHandling = automaticErrorHandling
|
||||
self.shouldUpgrade = shouldUpgrade
|
||||
self.upgradePipelineHandler = upgradePipelineHandler
|
||||
}
|
||||
}
|
||||
|
||||
class WebSocketServerEndToEndTests: XCTestCase {
|
||||
private func createTestFixtures(upgraders: [NIOWebSocketServerUpgrader]) -> (loop: EmbeddedEventLoop, serverChannel: EmbeddedChannel, clientChannel: EmbeddedChannel) {
|
||||
func createTestFixtures(
|
||||
upgraders: [WebSocketServerUpgraderConfiguration]
|
||||
) -> (loop: EmbeddedEventLoop, serverChannel: EmbeddedChannel, clientChannel: EmbeddedChannel) {
|
||||
let loop = EmbeddedEventLoop()
|
||||
let serverChannel = EmbeddedChannel(loop: loop)
|
||||
let upgraders = upgraders.map { NIOWebSocketServerUpgrader(
|
||||
maxFrameSize: $0.maxFrameSize,
|
||||
automaticErrorHandling: $0.automaticErrorHandling,
|
||||
shouldUpgrade: $0.shouldUpgrade,
|
||||
upgradePipelineHandler: $0.upgradePipelineHandler
|
||||
)}
|
||||
XCTAssertNoThrow(try serverChannel.pipeline.configureHTTPServerPipeline(
|
||||
withServerUpgrade: (upgraders: upgraders as [HTTPServerProtocolUpgrader], completionHandler: { (context: ChannelHandlerContext) in } )
|
||||
).wait())
|
||||
@@ -129,7 +157,7 @@ class WebSocketServerEndToEndTests: XCTestCase {
|
||||
}
|
||||
|
||||
func testBasicUpgradeDance() throws {
|
||||
let basicUpgrader = NIOWebSocketServerUpgrader(shouldUpgrade: { (channel, head) in channel.eventLoop.makeSucceededFuture(HTTPHeaders()) },
|
||||
let basicUpgrader = WebSocketServerUpgraderConfiguration(shouldUpgrade: { (channel, head) in channel.eventLoop.makeSucceededFuture(HTTPHeaders()) },
|
||||
upgradePipelineHandler: { (channel, req) in channel.eventLoop.makeSucceededFuture(()) })
|
||||
let (loop, server, client) = self.createTestFixtures(upgraders: [basicUpgrader])
|
||||
defer {
|
||||
@@ -151,7 +179,7 @@ class WebSocketServerEndToEndTests: XCTestCase {
|
||||
}
|
||||
|
||||
func testUpgradeWithProtocolName() throws {
|
||||
let basicUpgrader = NIOWebSocketServerUpgrader(shouldUpgrade: { (channel, head) in channel.eventLoop.makeSucceededFuture(HTTPHeaders()) },
|
||||
let basicUpgrader = WebSocketServerUpgraderConfiguration(shouldUpgrade: { (channel, head) in channel.eventLoop.makeSucceededFuture(HTTPHeaders()) },
|
||||
upgradePipelineHandler: { (channel, req) in channel.eventLoop.makeSucceededFuture(()) })
|
||||
let (loop, server, client) = self.createTestFixtures(upgraders: [basicUpgrader])
|
||||
defer {
|
||||
@@ -170,7 +198,7 @@ class WebSocketServerEndToEndTests: XCTestCase {
|
||||
}
|
||||
|
||||
func testCanRejectUpgrade() throws {
|
||||
let basicUpgrader = NIOWebSocketServerUpgrader(shouldUpgrade: { (channel, head) in channel.eventLoop.makeSucceededFuture(nil) },
|
||||
let basicUpgrader = WebSocketServerUpgraderConfiguration(shouldUpgrade: { (channel, head) in channel.eventLoop.makeSucceededFuture(nil) },
|
||||
upgradePipelineHandler: { (channel, req) in
|
||||
XCTFail("Should not have called")
|
||||
return channel.eventLoop.makeSucceededFuture(())
|
||||
@@ -201,7 +229,7 @@ class WebSocketServerEndToEndTests: XCTestCase {
|
||||
var acceptPromise: EventLoopPromise<HTTPHeaders?>? = nil
|
||||
var upgradeComplete = false
|
||||
|
||||
let basicUpgrader = NIOWebSocketServerUpgrader(shouldUpgrade: { (channel, head) in
|
||||
let basicUpgrader = WebSocketServerUpgraderConfiguration(shouldUpgrade: { (channel, head) in
|
||||
acceptPromise = channel.eventLoop.makePromise()
|
||||
return acceptPromise!.futureResult
|
||||
},
|
||||
@@ -240,7 +268,7 @@ class WebSocketServerEndToEndTests: XCTestCase {
|
||||
}
|
||||
|
||||
func testRequiresVersion13() throws {
|
||||
let basicUpgrader = NIOWebSocketServerUpgrader(shouldUpgrade: { (channel, head) in channel.eventLoop.makeSucceededFuture(HTTPHeaders()) },
|
||||
let basicUpgrader = WebSocketServerUpgraderConfiguration(shouldUpgrade: { (channel, head) in channel.eventLoop.makeSucceededFuture(HTTPHeaders()) },
|
||||
upgradePipelineHandler: { (channel, req) in channel.eventLoop.makeSucceededFuture(()) })
|
||||
let (loop, server, client) = self.createTestFixtures(upgraders: [basicUpgrader])
|
||||
defer {
|
||||
@@ -262,7 +290,7 @@ class WebSocketServerEndToEndTests: XCTestCase {
|
||||
}
|
||||
|
||||
func testRequiresVersionHeader() throws {
|
||||
let basicUpgrader = NIOWebSocketServerUpgrader(shouldUpgrade: { (channel, head) in channel.eventLoop.makeSucceededFuture(HTTPHeaders()) },
|
||||
let basicUpgrader = WebSocketServerUpgraderConfiguration(shouldUpgrade: { (channel, head) in channel.eventLoop.makeSucceededFuture(HTTPHeaders()) },
|
||||
upgradePipelineHandler: { (channel, req) in channel.eventLoop.makeSucceededFuture(()) })
|
||||
let (loop, server, client) = self.createTestFixtures(upgraders: [basicUpgrader])
|
||||
defer {
|
||||
@@ -284,7 +312,7 @@ class WebSocketServerEndToEndTests: XCTestCase {
|
||||
}
|
||||
|
||||
func testRequiresKeyHeader() throws {
|
||||
let basicUpgrader = NIOWebSocketServerUpgrader(shouldUpgrade: { (channel, head) in channel.eventLoop.makeSucceededFuture(HTTPHeaders()) },
|
||||
let basicUpgrader = WebSocketServerUpgraderConfiguration(shouldUpgrade: { (channel, head) in channel.eventLoop.makeSucceededFuture(HTTPHeaders()) },
|
||||
upgradePipelineHandler: { (channel, req) in channel.eventLoop.makeSucceededFuture(()) })
|
||||
let (loop, server, client) = self.createTestFixtures(upgraders: [basicUpgrader])
|
||||
defer {
|
||||
@@ -306,7 +334,7 @@ class WebSocketServerEndToEndTests: XCTestCase {
|
||||
}
|
||||
|
||||
func testUpgradeMayAddCustomHeaders() throws {
|
||||
let upgrader = NIOWebSocketServerUpgrader(shouldUpgrade: { (channel, head) in
|
||||
let upgrader = WebSocketServerUpgraderConfiguration(shouldUpgrade: { (channel, head) in
|
||||
var hdrs = HTTPHeaders()
|
||||
hdrs.add(name: "TestHeader", value: "TestValue")
|
||||
return channel.eventLoop.makeSucceededFuture(hdrs)
|
||||
@@ -329,8 +357,8 @@ class WebSocketServerEndToEndTests: XCTestCase {
|
||||
}
|
||||
|
||||
func testMayRegisterMultipleWebSocketEndpoints() throws {
|
||||
func buildHandler(path: String) -> NIOWebSocketServerUpgrader {
|
||||
return NIOWebSocketServerUpgrader(shouldUpgrade: { (channel, head) in
|
||||
func buildHandler(path: String) -> WebSocketServerUpgraderConfiguration {
|
||||
return WebSocketServerUpgraderConfiguration(shouldUpgrade: { (channel, head) in
|
||||
guard head.uri == "/\(path)" else { return channel.eventLoop.makeSucceededFuture(nil) }
|
||||
var hdrs = HTTPHeaders()
|
||||
hdrs.add(name: "Target", value: path)
|
||||
@@ -360,7 +388,7 @@ class WebSocketServerEndToEndTests: XCTestCase {
|
||||
|
||||
func testSendAFewFrames() throws {
|
||||
let recorder = WebSocketRecorderHandler()
|
||||
let basicUpgrader = NIOWebSocketServerUpgrader(shouldUpgrade: { (channel, head) in channel.eventLoop.makeSucceededFuture(HTTPHeaders()) },
|
||||
let basicUpgrader = WebSocketServerUpgraderConfiguration(shouldUpgrade: { (channel, head) in channel.eventLoop.makeSucceededFuture(HTTPHeaders()) },
|
||||
upgradePipelineHandler: { (channel, req) in
|
||||
channel.pipeline.addHandler(recorder)
|
||||
|
||||
@@ -398,7 +426,7 @@ class WebSocketServerEndToEndTests: XCTestCase {
|
||||
}
|
||||
|
||||
func testMaxFrameSize() throws {
|
||||
let basicUpgrader = NIOWebSocketServerUpgrader(maxFrameSize: 16, shouldUpgrade: { (channel, head) in channel.eventLoop.makeSucceededFuture(HTTPHeaders()) },
|
||||
let basicUpgrader = WebSocketServerUpgraderConfiguration(maxFrameSize: 16, shouldUpgrade: { (channel, head) in channel.eventLoop.makeSucceededFuture(HTTPHeaders()) },
|
||||
upgradePipelineHandler: { (channel, req) in
|
||||
return channel.eventLoop.makeSucceededFuture(())
|
||||
})
|
||||
@@ -423,7 +451,7 @@ class WebSocketServerEndToEndTests: XCTestCase {
|
||||
|
||||
func testAutomaticErrorHandling() throws {
|
||||
let recorder = WebSocketRecorderHandler()
|
||||
let basicUpgrader = NIOWebSocketServerUpgrader(shouldUpgrade: { (channel, head) in channel.eventLoop.makeSucceededFuture(HTTPHeaders()) },
|
||||
let basicUpgrader = WebSocketServerUpgraderConfiguration(shouldUpgrade: { (channel, head) in channel.eventLoop.makeSucceededFuture(HTTPHeaders()) },
|
||||
upgradePipelineHandler: { (channel, req) in
|
||||
channel.pipeline.addHandler(recorder)
|
||||
|
||||
@@ -461,7 +489,7 @@ class WebSocketServerEndToEndTests: XCTestCase {
|
||||
|
||||
func testNoAutomaticErrorHandling() throws {
|
||||
let recorder = WebSocketRecorderHandler()
|
||||
let basicUpgrader = NIOWebSocketServerUpgrader(automaticErrorHandling: false,
|
||||
let basicUpgrader = WebSocketServerUpgraderConfiguration(automaticErrorHandling: false,
|
||||
shouldUpgrade: { (channel, head) in channel.eventLoop.makeSucceededFuture(HTTPHeaders()) },
|
||||
upgradePipelineHandler: { (channel, req) in
|
||||
channel.pipeline.addHandler(recorder)
|
||||
@@ -498,3 +526,29 @@ class WebSocketServerEndToEndTests: XCTestCase {
|
||||
XCTAssertNoThrow(XCTAssertEqual([], try server.readAllOutboundBytes()))
|
||||
}
|
||||
}
|
||||
|
||||
final class TypedWebSocketServerEndToEndTests: WebSocketServerEndToEndTests {
|
||||
override func createTestFixtures(
|
||||
upgraders: [WebSocketServerUpgraderConfiguration]
|
||||
) -> (loop: EmbeddedEventLoop, serverChannel: EmbeddedChannel, clientChannel: EmbeddedChannel) {
|
||||
let loop = EmbeddedEventLoop()
|
||||
let serverChannel = EmbeddedChannel(loop: loop)
|
||||
let upgraders = upgraders.map { NIOTypedWebSocketServerUpgrader(
|
||||
maxFrameSize: $0.maxFrameSize,
|
||||
enableAutomaticErrorHandling: $0.automaticErrorHandling,
|
||||
shouldUpgrade: $0.shouldUpgrade,
|
||||
upgradePipelineHandler: $0.upgradePipelineHandler
|
||||
)}
|
||||
|
||||
XCTAssertNoThrow(try serverChannel.pipeline.syncOperations.configureUpgradableHTTPServerPipeline(
|
||||
configuration: .init(
|
||||
upgradeConfiguration: NIOTypedHTTPServerUpgradeConfiguration<Void>(
|
||||
upgraders: upgraders,
|
||||
notUpgradingCompletionHandler: { $0.eventLoop.makeSucceededVoidFuture() }
|
||||
)
|
||||
)
|
||||
))
|
||||
let clientChannel = EmbeddedChannel(loop: loop)
|
||||
return (loop: loop, serverChannel: serverChannel, clientChannel: clientChannel)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user