mirror of
https://github.com/apple/swift-nio
synced 2026-11-29 05:24:21 +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
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user