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:
Franz Busch authored and GitHub committed 2024-07-19 11:48:17 +02:00
1 parent 980bd3e630
commit c9756e1083
374 files changed
+23992 -14890

No files matched your search

+129 -46
View File
@@ -12,8 +12,8 @@
//
//===----------------------------------------------------------------------===//
import NIOCore
import NIOPosix
import NIOHTTP1
import NIOPosix
extension String {
func chopPrefix(_ prefix: String) -> String? {
@@ -34,7 +34,11 @@ extension String {
}
}
private func httpResponseHead(request: HTTPRequestHead, status: HTTPResponseStatus, headers: HTTPHeaders = HTTPHeaders()) -> HTTPResponseHead {
private func httpResponseHead(
request: HTTPRequestHead,
status: HTTPResponseStatus,
headers: HTTPHeaders = HTTPHeaders()
) -> HTTPResponseHead {
var head = HTTPResponseHead(version: request.version, status: status, headers: headers)
let connectionHeaders: [String] = head.headers[canonicalForm: "connection"].map { $0.lowercased() }
@@ -117,19 +121,24 @@ private final class HTTPHandler: ChannelInboundHandler {
case .end:
self.state.requestComplete()
let response = """
HTTP method: \(self.infoSavedRequestHead!.method)\r
URL: \(self.infoSavedRequestHead!.uri)\r
body length: \(self.infoSavedBodyBytes)\r
headers: \(self.infoSavedRequestHead!.headers)\r
client: \(context.remoteAddress?.description ?? "zombie")\r
IO: SwiftNIO Electric Boogaloo™️\r\n
"""
HTTP method: \(self.infoSavedRequestHead!.method)\r
URL: \(self.infoSavedRequestHead!.uri)\r
body length: \(self.infoSavedBodyBytes)\r
headers: \(self.infoSavedRequestHead!.headers)\r
client: \(context.remoteAddress?.description ?? "zombie")\r
IO: SwiftNIO Electric Boogaloo™️\r\n
"""
self.buffer.clear()
self.buffer.writeString(response)
var headers = HTTPHeaders()
headers.add(name: "Content-Length", value: "\(response.utf8.count)")
context.write(Self.wrapOutboundOut(.head(httpResponseHead(request: self.infoSavedRequestHead!, status: .ok, headers: headers))), promise: nil)
context.write(Self.wrapOutboundOut(.body(.byteBuffer(self.buffer))), promise: nil)
context.write(
Self.wrapOutboundOut(
.head(httpResponseHead(request: self.infoSavedRequestHead!, status: .ok, headers: headers))
),
promise: nil
)
context.write(self.wrapOutboundOut(.body(.byteBuffer(self.buffer))), promise: nil)
self.completeResponse(context, trailers: nil, promise: nil)
}
}
@@ -147,7 +156,10 @@ private final class HTTPHandler: ChannelInboundHandler {
if balloonInMemory {
self.buffer.clear()
} else {
context.writeAndFlush(Self.wrapOutboundOut(.head(httpResponseHead(request: request, status: .ok))), promise: nil)
context.writeAndFlush(
Self.wrapOutboundOut(.head(httpResponseHead(request: request, status: .ok))),
promise: nil
)
}
case .body(buffer: var buf):
if balloonInMemory {
@@ -160,8 +172,13 @@ private final class HTTPHandler: ChannelInboundHandler {
if balloonInMemory {
var headers = HTTPHeaders()
headers.add(name: "Content-Length", value: "\(self.buffer.readableBytes)")
context.write(Self.wrapOutboundOut(.head(httpResponseHead(request: self.infoSavedRequestHead!, status: .ok, headers: headers))), promise: nil)
context.write(Self.wrapOutboundOut(.body(.byteBuffer(self.buffer))), promise: nil)
context.write(
Self.wrapOutboundOut(
.head(httpResponseHead(request: self.infoSavedRequestHead!, status: .ok, headers: headers))
),
promise: nil
)
context.write(self.wrapOutboundOut(.body(.byteBuffer(self.buffer))), promise: nil)
self.completeResponse(context, trailers: nil, promise: nil)
} else {
self.completeResponse(context, trailers: nil, promise: nil)
@@ -169,12 +186,22 @@ private final class HTTPHandler: ChannelInboundHandler {
}
}
func handleJustWrite(context: ChannelHandlerContext, request: HTTPServerRequestPart, statusCode: HTTPResponseStatus = .ok, string: String, trailer: (String, String)? = nil, delay: TimeAmount = .nanoseconds(0)) {
func handleJustWrite(
context: ChannelHandlerContext,
request: HTTPServerRequestPart,
statusCode: HTTPResponseStatus = .ok,
string: String,
trailer: (String, String)? = nil,
delay: TimeAmount = .nanoseconds(0)
) {
switch request {
case .head(let request):
self.keepAlive = request.isKeepAlive
self.state.requestReceived()
context.writeAndFlush(Self.wrapOutboundOut(.head(httpResponseHead(request: request, status: statusCode))), promise: nil)
context.writeAndFlush(
Self.wrapOutboundOut(.head(httpResponseHead(request: request, status: statusCode))),
promise: nil
)
case .body(buffer: _):
()
case .end:
@@ -210,7 +237,10 @@ private final class HTTPHandler: ChannelInboundHandler {
self.completeResponse(context, trailers: nil, promise: nil)
}
}
context.writeAndFlush(Self.wrapOutboundOut(.head(httpResponseHead(request: request, status: .ok))), promise: nil)
context.writeAndFlush(
Self.wrapOutboundOut(.head(httpResponseHead(request: request, status: .ok))),
promise: nil
)
doNext()
case .end:
self.state.requestComplete()
@@ -219,7 +249,12 @@ private final class HTTPHandler: ChannelInboundHandler {
}
}
func handleMultipleWrites(context: ChannelHandlerContext, request: HTTPServerRequestPart, strings: [String], delay: TimeAmount) {
func handleMultipleWrites(
context: ChannelHandlerContext,
request: HTTPServerRequestPart,
strings: [String],
delay: TimeAmount
) {
switch request {
case .head(let request):
self.keepAlive = request.isKeepAlive
@@ -237,7 +272,10 @@ private final class HTTPHandler: ChannelInboundHandler {
}
}
}
context.writeAndFlush(Self.wrapOutboundOut(.head(httpResponseHead(request: request, status: .ok))), promise: nil)
context.writeAndFlush(
Self.wrapOutboundOut(.head(httpResponseHead(request: request, status: .ok))),
promise: nil
)
doNext()
case .end:
self.state.requestComplete()
@@ -249,9 +287,12 @@ private final class HTTPHandler: ChannelInboundHandler {
func dynamicHandler(request reqHead: HTTPRequestHead) -> ((ChannelHandlerContext, HTTPServerRequestPart) -> Void)? {
if let howLong = reqHead.uri.chopPrefix("/dynamic/write-delay/") {
return { context, req in
self.handleJustWrite(context: context,
request: req, string: self.defaultResponse,
delay: Int64(howLong).map { .milliseconds($0) } ?? .seconds(0))
self.handleJustWrite(
context: context,
request: req,
string: self.defaultResponse,
delay: Int64(howLong).map { .milliseconds($0) } ?? .seconds(0)
)
}
}
@@ -263,23 +304,57 @@ private final class HTTPHandler: ChannelInboundHandler {
case "/dynamic/pid":
return { context, req in self.handleJustWrite(context: context, request: req, string: "\(getpid())") }
case "/dynamic/write-delay":
return { context, req in self.handleJustWrite(context: context, request: req, string: self.defaultResponse, delay: .milliseconds(100)) }
return { context, req in
self.handleJustWrite(
context: context,
request: req,
string: self.defaultResponse,
delay: .milliseconds(100)
)
}
case "/dynamic/info":
return self.handleInfo
case "/dynamic/trailers":
return { context, req in self.handleJustWrite(context: context, request: req, string: "\(getpid())\r\n", trailer: ("Trailer-Key", "Trailer-Value")) }
return { context, req in
self.handleJustWrite(
context: context,
request: req,
string: "\(getpid())\r\n",
trailer: ("Trailer-Key", "Trailer-Value")
)
}
case "/dynamic/continuous":
return self.handleContinuousWrites
case "/dynamic/count-to-ten":
return { self.handleMultipleWrites(context: $0, request: $1, strings: (1...10).map { "\($0)" }, delay: .milliseconds(100)) }
return {
self.handleMultipleWrites(
context: $0,
request: $1,
strings: (1...10).map { "\($0)" },
delay: .milliseconds(100)
)
}
case "/dynamic/client-ip":
return { context, req in self.handleJustWrite(context: context, request: req, string: "\(context.remoteAddress.debugDescription)") }
return { context, req in
self.handleJustWrite(
context: context,
request: req,
string: "\(context.remoteAddress.debugDescription)"
)
}
default:
return { context, req in self.handleJustWrite(context: context, request: req, statusCode: .notFound, string: "not found") }
return { context, req in
self.handleJustWrite(context: context, request: req, statusCode: .notFound, string: "not found")
}
}
}
private func handleFile(context: ChannelHandlerContext, request: HTTPServerRequestPart, ioMethod: FileIOMethod, path: String) {
private func handleFile(
context: ChannelHandlerContext,
request: HTTPServerRequestPart,
ioMethod: FileIOMethod,
path: String
) {
self.buffer.clear()
func sendErrorResponse(request: HTTPRequestHead, _ error: Error) {
@@ -338,15 +413,17 @@ private final class HTTPHandler: ChannelInboundHandler {
responseStarted = true
context.write(Self.wrapOutboundOut(.head(response)), promise: nil)
}
return self.fileIO.readChunked(fileRegion: region,
chunkSize: 32 * 1024,
allocator: context.channel.allocator,
eventLoop: context.eventLoop) { buffer in
if !responseStarted {
responseStarted = true
context.write(Self.wrapOutboundOut(.head(response)), promise: nil)
}
return context.writeAndFlush(Self.wrapOutboundOut(.body(.byteBuffer(buffer))))
return self.fileIO.readChunked(
fileRegion: region,
chunkSize: 32 * 1024,
allocator: context.channel.allocator,
eventLoop: context.eventLoop
) { buffer in
if !responseStarted {
responseStarted = true
context.write(Self.wrapOutboundOut(.head(response)), promise: nil)
}
return context.writeAndFlush(Self.wrapOutboundOut(.body(.byteBuffer(buffer))))
}.flatMap { () -> EventLoopFuture<Void> in
let p = context.eventLoop.makePromise(of: Void.self)
self.completeResponse(context, trailers: nil, promise: p)
@@ -379,7 +456,7 @@ private final class HTTPHandler: ChannelInboundHandler {
_ = try? file.close()
}
}
}
}
case .end:
self.state.requestComplete()
default:
@@ -387,7 +464,11 @@ private final class HTTPHandler: ChannelInboundHandler {
}
}
private func completeResponse(_ context: ChannelHandlerContext, trailers: HTTPHeaders?, promise: EventLoopPromise<Void>?) {
private func completeResponse(
_ context: ChannelHandlerContext,
trailers: HTTPHeaders?,
promise: EventLoopPromise<Void>?
) {
self.state.responseComplete()
let promise = self.keepAlive ? promise : (promise ?? context.eventLoop.makePromise())
@@ -469,7 +550,7 @@ private final class HTTPHandler: ChannelInboundHandler {
}
// First argument is the program path
var arguments = CommandLine.arguments.dropFirst(0) // just to get an ArraySlice<String> from [String]
var arguments = CommandLine.arguments.dropFirst(0) // just to get an ArraySlice<String> from [String]
var allowHalfClosure = true
if arguments.dropFirst().first == .some("--disable-half-closure") {
allowHalfClosure = false
@@ -493,16 +574,16 @@ let htdocs: String
let bindTarget: BindTo
switch (arg1, arg1.flatMap(Int.init), arg2, arg2.flatMap(Int.init), arg3) {
case (.some(let h), _ , _, .some(let p), let maybeHtdocs):
/* second arg an integer --> host port [htdocs] */
case (.some(let h), _, _, .some(let p), let maybeHtdocs):
// second arg an integer --> host port [htdocs]
bindTarget = .ip(host: h, port: p)
htdocs = maybeHtdocs ?? defaultHtdocs
case (_, .some(let p), let maybeHtdocs, _, _):
/* first arg an integer --> port [htdocs] */
// first arg an integer --> port [htdocs]
bindTarget = .ip(host: defaultHost, port: p)
htdocs = maybeHtdocs ?? defaultHtdocs
case (.some(let portString), .none, let maybeHtdocs, .none, .none):
/* couldn't parse as number --> uds-path-or-stdio [htdocs] */
// couldn't parse as number --> uds-path-or-stdio [htdocs]
if portString == "-" {
bindTarget = .stdio
} else {
@@ -515,7 +596,7 @@ default:
}
func childChannelInitializer(channel: Channel) -> EventLoopFuture<Void> {
return channel.pipeline.configureHTTPServerPipeline(withErrorHandling: true).flatMap {
channel.pipeline.configureHTTPServerPipeline(withErrorHandling: true).flatMap {
channel.pipeline.addHandler(HTTPHandler(fileIO: fileIO, htdocsPath: htdocs))
}
}
@@ -557,7 +638,9 @@ if case .stdio = bindTarget {
localAddress = "STDIO"
} else {
guard let channelLocalAddress = channel.localAddress else {
fatalError("Address was unable to bind. Please check that the socket was not closed or that the address family was understood.")
fatalError(
"Address was unable to bind. Please check that the socket was not closed or that the address family was understood."
)
}
localAddress = "\(channelLocalAddress)"
}