mirror of
https://github.com/apple/swift-nio
synced 2026-11-25 04:47:49 +00:00
Adopt swift-format (#2794)
* Apply formatting
* Apply no block comments rule
* Apply OmitExplicitReturns
* Apple OnlyOneTrailingClosureArgument
* Apply NoAssignmentInExpressions
* Fix up DontRepeatTypeInStaticProperties lint errors
* Apply `OrderedImports`
* Apply `ReplaceForEachWithForLoop`
* format file
* Enable the formatting pipeline
* Adopt `AmbiguousTrailingClosureOverload`
* Fix license header
* Fix format check
* Fix `EndOfLineComment`
* Fix CI
* Adapt CI script to check if changes when running formatting
* Separate lint and format into to steps
* Fix format
* Adopt `UseEarlyExits`
* Revert "Adopt `UseEarlyExits`"
This reverts commit d1ac5bbe12.
This commit is contained in:
1 parent
980bd3e630
commit
c9756e1083
374 files changed
+23992
-14890
No files matched your search
@@ -27,9 +27,9 @@ public struct NIOHTTPClientUpgradeError: Hashable, Error {
|
||||
case receivedResponseBeforeRequestSent
|
||||
case receivedResponseAfterUpgradeCompleted
|
||||
}
|
||||
|
||||
|
||||
private var code: Code
|
||||
|
||||
|
||||
private init(_ code: Code) {
|
||||
self.code = code
|
||||
}
|
||||
@@ -38,15 +38,21 @@ public struct NIOHTTPClientUpgradeError: Hashable, Error {
|
||||
public static let invalidHTTPOrdering = NIOHTTPClientUpgradeError(.invalidHTTPOrdering)
|
||||
public static let upgraderDeniedUpgrade = NIOHTTPClientUpgradeError(.upgraderDeniedUpgrade)
|
||||
public static let writingToHandlerDuringUpgrade = NIOHTTPClientUpgradeError(.writingToHandlerDuringUpgrade)
|
||||
public static let writingToHandlerAfterUpgradeCompleted = NIOHTTPClientUpgradeError(.writingToHandlerAfterUpgradeCompleted)
|
||||
public static let writingToHandlerAfterUpgradeFailed = NIOHTTPClientUpgradeError(.writingToHandlerAfterUpgradeFailed)
|
||||
public static let writingToHandlerAfterUpgradeCompleted = NIOHTTPClientUpgradeError(
|
||||
.writingToHandlerAfterUpgradeCompleted
|
||||
)
|
||||
public static let writingToHandlerAfterUpgradeFailed = NIOHTTPClientUpgradeError(
|
||||
.writingToHandlerAfterUpgradeFailed
|
||||
)
|
||||
public static let receivedResponseBeforeRequestSent = NIOHTTPClientUpgradeError(.receivedResponseBeforeRequestSent)
|
||||
public static let receivedResponseAfterUpgradeCompleted = NIOHTTPClientUpgradeError(.receivedResponseAfterUpgradeCompleted)
|
||||
public static let receivedResponseAfterUpgradeCompleted = NIOHTTPClientUpgradeError(
|
||||
.receivedResponseAfterUpgradeCompleted
|
||||
)
|
||||
}
|
||||
|
||||
extension NIOHTTPClientUpgradeError: CustomStringConvertible {
|
||||
public var description: String {
|
||||
return String(describing: self.code)
|
||||
String(describing: self.code)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,21 +60,21 @@ extension NIOHTTPClientUpgradeError: CustomStringConvertible {
|
||||
/// a protocol on a client-side channel.
|
||||
/// It has the option of denying this upgrade based upon the server response.
|
||||
public protocol NIOHTTPClientProtocolUpgrader {
|
||||
|
||||
|
||||
/// The protocol this upgrader knows how to support.
|
||||
var supportedProtocol: String { get }
|
||||
|
||||
|
||||
/// All the header fields the protocol requires in the request to successfully upgrade.
|
||||
/// These header fields will be added to the outbound request's "Connection" header field.
|
||||
/// It is the responsibility of the custom headers call to actually add these required headers.
|
||||
var requiredUpgradeHeaders: [String] { get }
|
||||
|
||||
|
||||
/// Additional headers to be added to the request, beyond the "Upgrade" and "Connection" headers.
|
||||
func addCustom(upgradeRequestHeaders: inout HTTPHeaders)
|
||||
|
||||
|
||||
/// Gives the receiving upgrader the chance to deny the upgrade based on the upgrade HTTP response.
|
||||
func shouldAllowUpgrade(upgradeResponse: HTTPResponseHead) -> Bool
|
||||
|
||||
|
||||
/// 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.
|
||||
@@ -85,24 +91,24 @@ public protocol NIOHTTPClientProtocolUpgrader {
|
||||
/// It will only upgrade to the protocol that is returned first in the list and does not currently
|
||||
/// have the capability to upgrade to multiple simultaneous layered protocols.
|
||||
public final class NIOHTTPClientUpgradeHandler: ChannelDuplexHandler, RemovableChannelHandler {
|
||||
|
||||
|
||||
public typealias OutboundIn = HTTPClientRequestPart
|
||||
public typealias OutboundOut = HTTPClientRequestPart
|
||||
|
||||
public typealias InboundIn = HTTPClientResponsePart
|
||||
public typealias InboundOut = HTTPClientResponsePart
|
||||
|
||||
|
||||
private var upgraders: [NIOHTTPClientProtocolUpgrader]
|
||||
private let httpHandlers: [RemovableChannelHandler]
|
||||
private let upgradeCompletionHandler: (ChannelHandlerContext) -> Void
|
||||
|
||||
|
||||
/// Whether we've already seen the first response from our initial upgrade request.
|
||||
private var seenFirstResponse = false
|
||||
|
||||
|
||||
private var upgradeState: UpgradeState = .requestRequired
|
||||
|
||||
|
||||
private var receivedMessages: CircularBuffer<NIOAny> = CircularBuffer()
|
||||
|
||||
|
||||
/// Create a `HTTPClientUpgradeHandler`.
|
||||
///
|
||||
/// - Parameter upgraders: All `HTTPClientProtocolUpgrader` objects that will add their upgrade request
|
||||
@@ -121,7 +127,7 @@ public final class NIOHTTPClientUpgradeHandler: ChannelDuplexHandler, RemovableC
|
||||
) {
|
||||
self.init(_upgraders: upgraders, httpHandlers: httpHandlers, upgradeCompletionHandler: upgradeCompletionHandler)
|
||||
}
|
||||
|
||||
|
||||
private init(
|
||||
_upgraders upgraders: [NIOHTTPClientProtocolUpgrader],
|
||||
httpHandlers: [RemovableChannelHandler],
|
||||
@@ -137,7 +143,7 @@ public final class NIOHTTPClientUpgradeHandler: ChannelDuplexHandler, RemovableC
|
||||
public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
|
||||
|
||||
switch self.upgradeState {
|
||||
|
||||
|
||||
case .requestRequired:
|
||||
let updatedData = self.addHeadersToOutboundOut(data: data)
|
||||
context.write(updatedData, promise: promise)
|
||||
@@ -145,7 +151,7 @@ public final class NIOHTTPClientUpgradeHandler: ChannelDuplexHandler, RemovableC
|
||||
case .awaitingConfirmationResponse:
|
||||
// Still have full http stack.
|
||||
context.write(data, promise: promise)
|
||||
|
||||
|
||||
case .upgraderReady, .upgrading:
|
||||
promise?.fail(NIOHTTPClientUpgradeError.writingToHandlerDuringUpgrade)
|
||||
context.fireErrorCaught(NIOHTTPClientUpgradeError.writingToHandlerDuringUpgrade)
|
||||
@@ -154,7 +160,7 @@ public final class NIOHTTPClientUpgradeHandler: ChannelDuplexHandler, RemovableC
|
||||
// These are most likely messages immediately fired by a new protocol handler.
|
||||
// As that is added last we can just forward them on.
|
||||
context.write(data, promise: promise)
|
||||
|
||||
|
||||
case .upgradeComplete:
|
||||
// Upgrade complete and this handler should have been removed from the pipeline.
|
||||
promise?.fail(NIOHTTPClientUpgradeError.writingToHandlerAfterUpgradeCompleted)
|
||||
@@ -168,18 +174,18 @@ public final class NIOHTTPClientUpgradeHandler: ChannelDuplexHandler, RemovableC
|
||||
}
|
||||
|
||||
private func addHeadersToOutboundOut(data: NIOAny) -> NIOAny {
|
||||
|
||||
|
||||
let interceptedOutgoingRequest = Self.unwrapOutboundIn(data)
|
||||
|
||||
|
||||
if case .head(var requestHead) = interceptedOutgoingRequest {
|
||||
|
||||
|
||||
self.upgradeState = .awaitingConfirmationResponse
|
||||
|
||||
|
||||
self.addConnectionHeaders(to: &requestHead)
|
||||
self.addUpgradeHeaders(to: &requestHead)
|
||||
return Self.wrapOutboundOut(.head(requestHead))
|
||||
}
|
||||
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
@@ -190,7 +196,7 @@ public final class NIOHTTPClientUpgradeHandler: ChannelDuplexHandler, RemovableC
|
||||
}
|
||||
|
||||
private func addUpgradeHeaders(to requestHead: inout HTTPRequestHead) {
|
||||
|
||||
|
||||
let allProtocols = self.upgraders.map { $0.supportedProtocol.lowercased() }
|
||||
requestHead.headers.add(name: "Upgrade", value: allProtocols.joined(separator: ","))
|
||||
|
||||
@@ -199,9 +205,9 @@ public final class NIOHTTPClientUpgradeHandler: ChannelDuplexHandler, RemovableC
|
||||
upgrader.addCustom(upgradeRequestHeaders: &requestHead.headers)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
|
||||
|
||||
|
||||
guard !self.seenFirstResponse else {
|
||||
// We're waiting for upgrade to complete: buffer this data.
|
||||
self.receivedMessages.append(data)
|
||||
@@ -235,9 +241,9 @@ public final class NIOHTTPClientUpgradeHandler: ChannelDuplexHandler, RemovableC
|
||||
context.fireErrorCaught(NIOHTTPClientUpgradeError.receivedResponseBeforeRequestSent)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private func firstResponseHeadReceived(context: ChannelHandlerContext, responsePart: HTTPClientResponsePart) {
|
||||
|
||||
|
||||
// We should decide if we're can upgrade based on the first response header: if we aren't upgrading,
|
||||
// by the time the body comes in we should be out of the pipeline. That means that if we don't think we're
|
||||
// upgrading, the only thing we should see is a response head. Anything else in an error.
|
||||
@@ -245,7 +251,7 @@ public final class NIOHTTPClientUpgradeHandler: ChannelDuplexHandler, RemovableC
|
||||
self.notUpgrading(context: context, data: responsePart, error: .invalidHTTPOrdering)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
// Assess whether the upgrade response has accepted our upgrade request.
|
||||
guard case .switchingProtocols = response.status else {
|
||||
self.notUpgrading(context: context, data: responsePart, error: nil)
|
||||
@@ -260,44 +266,57 @@ public final class NIOHTTPClientUpgradeHandler: ChannelDuplexHandler, RemovableC
|
||||
self.notUpgrading(context: context, data: responsePart, error: clientError)
|
||||
}
|
||||
}
|
||||
|
||||
private func handleUpgrade(context: ChannelHandlerContext, upgradeResponse response: HTTPResponseHead) throws -> (() -> Void) {
|
||||
|
||||
private func handleUpgrade(
|
||||
context: ChannelHandlerContext,
|
||||
upgradeResponse response: HTTPResponseHead
|
||||
) throws -> (() -> Void) {
|
||||
|
||||
// Ok, we have a HTTP response. Check if it's an upgrade confirmation.
|
||||
// If it's not, we want to pass it on and remove ourselves from the channel pipeline.
|
||||
let acceptedProtocols = response.headers[canonicalForm: "upgrade"]
|
||||
|
||||
|
||||
// At the moment we only upgrade to the first protocol returned from the server.
|
||||
guard let protocolName = acceptedProtocols.first?.lowercased() else {
|
||||
// There are no upgrade protocols returned.
|
||||
throw NIOHTTPClientUpgradeError.responseProtocolNotFound
|
||||
}
|
||||
|
||||
return try self.handleUpgradeForProtocol(context: context,
|
||||
protocolName: protocolName,
|
||||
response: response)
|
||||
return try self.handleUpgradeForProtocol(
|
||||
context: context,
|
||||
protocolName: protocolName,
|
||||
response: response
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
/// Attempt to upgrade a single protocol.
|
||||
private func handleUpgradeForProtocol(context: ChannelHandlerContext, protocolName: String, response: HTTPResponseHead) throws -> (() -> Void) {
|
||||
private func handleUpgradeForProtocol(
|
||||
context: ChannelHandlerContext,
|
||||
protocolName: String,
|
||||
response: HTTPResponseHead
|
||||
) throws -> (() -> Void) {
|
||||
|
||||
let matchingUpgrader = self.upgraders
|
||||
.first(where: { $0.supportedProtocol.lowercased() == protocolName })
|
||||
|
||||
|
||||
guard let upgrader = matchingUpgrader else {
|
||||
// There is no upgrader for this protocol.
|
||||
throw NIOHTTPClientUpgradeError.responseProtocolNotFound
|
||||
}
|
||||
|
||||
|
||||
guard upgrader.shouldAllowUpgrade(upgradeResponse: response) else {
|
||||
// The upgrader says no.
|
||||
throw NIOHTTPClientUpgradeError.upgraderDeniedUpgrade
|
||||
}
|
||||
|
||||
|
||||
return self.performUpgrade(context: context, upgrader: upgrader, response: response)
|
||||
}
|
||||
|
||||
private func performUpgrade(context: ChannelHandlerContext, upgrader: NIOHTTPClientProtocolUpgrader, response: HTTPResponseHead) -> () -> Void {
|
||||
|
||||
private func performUpgrade(
|
||||
context: ChannelHandlerContext,
|
||||
upgrader: NIOHTTPClientProtocolUpgrader,
|
||||
response: HTTPResponseHead
|
||||
) -> () -> Void {
|
||||
|
||||
// Before we start the upgrade we have to remove the HTTPEncoder and HTTPDecoder handlers from the
|
||||
// pipeline, to prevent them parsing any more data. We'll buffer the incoming data until that completes.
|
||||
@@ -306,52 +325,52 @@ public final class NIOHTTPClientUpgradeHandler: ChannelDuplexHandler, RemovableC
|
||||
// Once that's done, we call the internal handler, then call the upgrader code, and then finally when the
|
||||
// upgrader 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.
|
||||
return {
|
||||
{
|
||||
self.upgradeState = .upgrading
|
||||
|
||||
|
||||
self.removeHTTPHandlers(context: context)
|
||||
.map {
|
||||
// Let the other handlers be removed before continuing with upgrade.
|
||||
self.upgradeCompletionHandler(context)
|
||||
self.upgradeState = .upgradingAddingHandlers
|
||||
}
|
||||
.flatMap {
|
||||
upgrader.upgrade(context: context, upgradeResponse: response)
|
||||
}
|
||||
.map {
|
||||
// We unbuffer any buffered data here.
|
||||
|
||||
// If we received any, we fire readComplete.
|
||||
let fireReadComplete = self.receivedMessages.count > 0
|
||||
while self.receivedMessages.count > 0 {
|
||||
let bufferedPart = self.receivedMessages.removeFirst()
|
||||
context.fireChannelRead(bufferedPart)
|
||||
.map {
|
||||
// Let the other handlers be removed before continuing with upgrade.
|
||||
self.upgradeCompletionHandler(context)
|
||||
self.upgradeState = .upgradingAddingHandlers
|
||||
}
|
||||
if fireReadComplete {
|
||||
context.fireChannelReadComplete()
|
||||
.flatMap {
|
||||
upgrader.upgrade(context: context, upgradeResponse: response)
|
||||
}
|
||||
.map {
|
||||
// We unbuffer any buffered data here.
|
||||
|
||||
// If we received any, we fire readComplete.
|
||||
let fireReadComplete = self.receivedMessages.count > 0
|
||||
while self.receivedMessages.count > 0 {
|
||||
let bufferedPart = self.receivedMessages.removeFirst()
|
||||
context.fireChannelRead(bufferedPart)
|
||||
}
|
||||
if fireReadComplete {
|
||||
context.fireChannelReadComplete()
|
||||
}
|
||||
|
||||
// We wait with the state change until _after_ the channel reads here.
|
||||
// This is to prevent firing writes in response to these reads after we went to .upgradeComplete
|
||||
// See: https://github.com/apple/swift-nio/issues/1279
|
||||
self.upgradeState = .upgradeComplete
|
||||
}
|
||||
.whenComplete { _ in
|
||||
context.pipeline.removeHandler(context: context, promise: nil)
|
||||
}
|
||||
|
||||
// We wait with the state change until _after_ the channel reads here.
|
||||
// This is to prevent firing writes in response to these reads after we went to .upgradeComplete
|
||||
// See: https://github.com/apple/swift-nio/issues/1279
|
||||
self.upgradeState = .upgradeComplete
|
||||
}
|
||||
.whenComplete { _ in
|
||||
context.pipeline.removeHandler(context: context, promise: nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Removes any extra HTTP-related handlers from the channel pipeline.
|
||||
private func removeHTTPHandlers(context: ChannelHandlerContext) -> EventLoopFuture<Void> {
|
||||
guard self.httpHandlers.count > 0 else {
|
||||
return context.eventLoop.makeSucceededFuture(())
|
||||
}
|
||||
|
||||
|
||||
let removeFutures = self.httpHandlers.map { context.pipeline.removeHandler($0) }
|
||||
return .andAllSucceed(removeFutures, on: context.eventLoop)
|
||||
}
|
||||
|
||||
|
||||
private func gotUpgrader(upgrader: @escaping (() -> Void)) {
|
||||
|
||||
self.upgradeState = .upgraderReady(upgrader)
|
||||
@@ -362,17 +381,21 @@ public final class NIOHTTPClientUpgradeHandler: ChannelDuplexHandler, RemovableC
|
||||
}
|
||||
}
|
||||
|
||||
private func notUpgrading(context: ChannelHandlerContext, data: HTTPClientResponsePart, error: NIOHTTPClientUpgradeError?) {
|
||||
|
||||
private func notUpgrading(
|
||||
context: ChannelHandlerContext,
|
||||
data: HTTPClientResponsePart,
|
||||
error: NIOHTTPClientUpgradeError?
|
||||
) {
|
||||
|
||||
self.upgradeState = .upgradeFailed
|
||||
|
||||
|
||||
if let error = error {
|
||||
context.fireErrorCaught(error)
|
||||
}
|
||||
|
||||
|
||||
assert(self.receivedMessages.isEmpty)
|
||||
context.fireChannelRead(Self.wrapInboundOut(data))
|
||||
|
||||
|
||||
// We've delivered the data. We can now remove ourselves, which should happen synchronously.
|
||||
context.pipeline.removeHandler(context: context, promise: nil)
|
||||
}
|
||||
@@ -388,19 +411,19 @@ extension NIOHTTPClientUpgradeHandler {
|
||||
|
||||
/// Awaiting confirmation response which will allow the upgrade to zero one or more protocols.
|
||||
case awaitingConfirmationResponse
|
||||
|
||||
|
||||
/// The response head has been received. We have an upgrader, which means we can begin upgrade.
|
||||
case upgraderReady(() -> Void)
|
||||
|
||||
|
||||
/// The response head has been received. The upgrade is in process.
|
||||
case upgrading
|
||||
|
||||
|
||||
/// The upgrade is in process and all of the http handlers have been removed.
|
||||
case upgradingAddingHandlers
|
||||
|
||||
|
||||
/// The upgrade has succeeded, and we are being removed from the pipeline.
|
||||
case upgradeComplete
|
||||
|
||||
|
||||
/// The upgrade has failed.
|
||||
case upgradeFailed
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user