Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Apply swift-format changes and CI #472

Merged
merged 8 commits into from
Oct 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
root = true

[*]
indent_style = space
indent_size = 4
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
2 changes: 1 addition & 1 deletion .github/workflows/pull_request.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ jobs:
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@main
with:
license_header_check_project_name: "SwiftNIO"
format_check_enabled: false
format_check_enabled: true
shell_check_enabled: false

unit-tests:
Expand Down
62 changes: 62 additions & 0 deletions .swift-format
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
{
"version" : 1,
"indentation" : {
"spaces" : 4
},
"tabWidth" : 4,
"fileScopedDeclarationPrivacy" : {
"accessLevel" : "private"
},
"spacesAroundRangeFormationOperators" : false,
"indentConditionalCompilationBlocks" : false,
"indentSwitchCaseLabels" : false,
"lineBreakAroundMultilineExpressionChainComponents" : false,
"lineBreakBeforeControlFlowKeywords" : false,
"lineBreakBeforeEachArgument" : true,
"lineBreakBeforeEachGenericRequirement" : true,
"lineLength" : 120,
"maximumBlankLines" : 1,
"respectsExistingLineBreaks" : true,
"prioritizeKeepingFunctionOutputTogether" : true,
"rules" : {
"AllPublicDeclarationsHaveDocumentation" : false,
"AlwaysUseLiteralForEmptyCollectionInit" : false,
"AlwaysUseLowerCamelCase" : false,
"AmbiguousTrailingClosureOverload" : true,
"BeginDocumentationCommentWithOneLineSummary" : false,
"DoNotUseSemicolons" : true,
"DontRepeatTypeInStaticProperties" : true,
"FileScopedDeclarationPrivacy" : true,
"FullyIndirectEnum" : true,
"GroupNumericLiterals" : true,
"IdentifiersMustBeASCII" : true,
"NeverForceUnwrap" : false,
"NeverUseForceTry" : false,
"NeverUseImplicitlyUnwrappedOptionals" : false,
"NoAccessLevelOnExtensionDeclaration" : true,
"NoAssignmentInExpressions" : true,
"NoBlockComments" : true,
"NoCasesWithOnlyFallthrough" : true,
"NoEmptyTrailingClosureParentheses" : true,
"NoLabelsInCasePatterns" : true,
"NoLeadingUnderscores" : false,
"NoParensAroundConditions" : true,
"NoVoidReturnOnFunctionSignature" : true,
"OmitExplicitReturns" : true,
"OneCasePerLine" : true,
"OneVariableDeclarationPerLine" : true,
"OnlyOneTrailingClosureArgument" : true,
"OrderedImports" : true,
"ReplaceForEachWithForLoop" : true,
"ReturnVoidInsteadOfEmptyTuple" : true,
"UseEarlyExits" : false,
"UseExplicitNilCheckInConditions" : false,
"UseLetInEveryBoundCaseVariable" : false,
"UseShorthandTypeNames" : true,
"UseSingleLinePropertyGetter" : false,
"UseSynthesizedInitializer" : false,
"UseTripleSlashForDocumentationComments" : true,
"UseWhereClausesInForLoops" : false,
"ValidateDocumentationComments" : false
}
}
2 changes: 1 addition & 1 deletion FuzzTesting/Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,6 @@ let package = Package(
.product(name: "NIOCore", package: "swift-nio"),
.product(name: "NIOEmbedded", package: "swift-nio"),
]
),
)
]
)
20 changes: 9 additions & 11 deletions FuzzTesting/Sources/FuzzHTTP2/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,22 +19,20 @@
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt


import Foundation

import NIOCore
import NIOEmbedded
import NIOHTTP1
import NIOHTTP2

fileprivate func fuzzInput(_ bytes: UnsafeRawBufferPointer) throws {
private func fuzzInput(_ bytes: UnsafeRawBufferPointer) throws {
let channel = EmbeddedChannel()
defer {
_ = try? channel.finish()
}
_ = try channel.configureHTTP2Pipeline(
mode: .server,
initialLocalSettings: [HTTP2Setting(parameter: .maxConcurrentStreams, value: 1<<23)],
initialLocalSettings: [HTTP2Setting(parameter: .maxConcurrentStreams, value: 1 << 23)],
inboundStreamInitializer: nil
).wait()
try channel.connect(to: SocketAddress(unixDomainSocketPath: "/foo")).wait()
Expand All @@ -48,12 +46,12 @@ fileprivate func fuzzInput(_ bytes: UnsafeRawBufferPointer) throws {

@_cdecl("LLVMFuzzerTestOneInput")
public func FuzzServer(_ start: UnsafeRawPointer, _ count: Int) -> CInt {
let bytes = UnsafeRawBufferPointer(start: start, count: count)
do {
let _ = try fuzzInput(bytes)
} catch {
// Errors parsing are to be expected since not all inputs will be well formed.
}
let bytes = UnsafeRawBufferPointer(start: start, count: count)
do {
let _ = try fuzzInput(bytes)
} catch {
// Errors parsing are to be expected since not all inputs will be well formed.
}

return 0
return 0
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,27 @@ import NIOHTTP2

/// Test use only. Allows abstracting over the two multiplexer implementations to write common testing code
internal protocol MultiplexerChannelCreator {
func createStreamChannel(promise: EventLoopPromise<Channel>?, _ streamStateInitializer: @escaping NIOHTTP2Handler.StreamInitializer)
func createStreamChannel(
promise: EventLoopPromise<Channel>?,
_ streamStateInitializer: @escaping NIOHTTP2Handler.StreamInitializer
)
func createStreamChannel(_ initializer: @escaping NIOChannelInitializer) -> EventLoopFuture<Channel>
}

extension HTTP2StreamMultiplexer: MultiplexerChannelCreator { }
extension NIOHTTP2Handler.StreamMultiplexer: MultiplexerChannelCreator { }
extension HTTP2StreamMultiplexer: MultiplexerChannelCreator {}
extension NIOHTTP2Handler.StreamMultiplexer: MultiplexerChannelCreator {}

/// Have two `EmbeddedChannel` objects send and receive data from each other until
/// they make no forward progress.
func interactInMemory(_ first: EmbeddedChannel, _ second: EmbeddedChannel) throws {
precondition(first.eventLoop === second.eventLoop, "interactInMemory assumes both channels are on the same event loop.")
precondition(
first.eventLoop === second.eventLoop,
"interactInMemory assumes both channels are on the same event loop."
)
var operated: Bool

func readBytesFromChannel(_ channel: EmbeddedChannel) throws -> ByteBuffer? {
return try channel.readOutbound(as: ByteBuffer.self)
try channel.readOutbound(as: ByteBuffer.self)
}

repeat {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,12 @@ struct ServerOnly1KRequestsBenchmark {
headers.add(name: ":authority", value: "localhost", indexing: .nonIndexable)
headers.add(name: ":path", value: "/", indexing: .indexable)
headers.add(name: ":scheme", value: "https", indexing: .indexable)
headers.add(name: "user-agent",
value: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36",
indexing: .nonIndexable)
headers.add(
name: "user-agent",
value:
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36",
indexing: .nonIndexable
)
headers.add(name: "accept-encoding", value: "gzip, deflate", indexing: .indexable)

var hpackEncoder = HPACKEncoder(allocator: .init())
Expand Down Expand Up @@ -108,7 +111,7 @@ struct ServerOnly1KRequestsBenchmark {
return settingsCopy
}

init(concurrentStreams: Int, pipelineConfigurator: (Channel) throws -> ()) throws {
init(concurrentStreams: Int, pipelineConfigurator: (Channel) throws -> Void) throws {
self.concurrentStreams = concurrentStreams

self.channel = EmbeddedChannel()
Expand All @@ -122,7 +125,7 @@ struct ServerOnly1KRequestsBenchmark {
initialBytes.writeImmutableBuffer(self.settingsACK)

try self.channel.writeInbound(initialBytes)
while try self.channel.readOutbound(as: ByteBuffer.self) != nil { }
while try self.channel.readOutbound(as: ByteBuffer.self) != nil {}
}

func tearDown() {
Expand All @@ -142,15 +145,15 @@ struct ServerOnly1KRequestsBenchmark {
private mutating func sendInterleavedRequests(_ interleavedRequests: Int) throws -> Int {
var streamID = self.streamID

for _ in 0 ..< interleavedRequests {
for _ in 0..<interleavedRequests {
self.headersFrame.setInteger(UInt32(Int32(streamID)), at: self.headersFrame.readerIndex + 5)
try self.channel.writeInbound(self.headersFrame)
streamID = streamID.advanced(by: 2)
}

streamID = self.streamID

for _ in 0 ..< interleavedRequests {
for _ in 0..<interleavedRequests {
self.dataFrame.setInteger(UInt32(Int32(streamID)), at: self.dataFrame.readerIndex + 5)
try self.channel.writeInbound(self.dataFrame)
streamID = streamID.advanced(by: 2)
Expand All @@ -169,7 +172,7 @@ struct ServerOnly1KRequestsBenchmark {
}
}

fileprivate class TestServer: ChannelInboundHandler {
private class TestServer: ChannelInboundHandler {
public typealias InboundIn = HTTP2Frame.FramePayload
public typealias OutboundOut = HTTP2Frame.FramePayload

Expand Down Expand Up @@ -198,50 +201,58 @@ fileprivate class TestServer: ChannelInboundHandler {
func run(identifier: String) {
var interleaved = try! ServerOnly1KRequestsBenchmark(concurrentStreams: 100) { channel in
_ = try channel.configureHTTP2Pipeline(mode: .server) { streamChannel -> EventLoopFuture<Void> in
return streamChannel.pipeline.addHandler(TestServer())
streamChannel.pipeline.addHandler(TestServer())
}.wait()
}

measure(identifier: identifier + "_interleaved") {
return try! interleaved.run()
try! interleaved.run()
}

interleaved.tearDown()

var noninterleaved = try! ServerOnly1KRequestsBenchmark(concurrentStreams: 1) { channel in
_ = try channel.configureHTTP2Pipeline(mode: .server) { streamChannel -> EventLoopFuture<Void> in
return streamChannel.pipeline.addHandler(TestServer())
streamChannel.pipeline.addHandler(TestServer())
}.wait()
}

measure(identifier: identifier + "_noninterleaved") {
return try! noninterleaved.run()
try! noninterleaved.run()
}

noninterleaved.tearDown()

//
// MARK: - Inline HTTP2 multiplexer tests
var inlineInterleaved = try! ServerOnly1KRequestsBenchmark(concurrentStreams: 100) { channel in
_ = try channel.configureHTTP2Pipeline(mode: .server, connectionConfiguration: .init(), streamConfiguration: .init()) { streamChannel -> EventLoopFuture<Void> in
return streamChannel.pipeline.addHandler(TestServer())
_ = try channel.configureHTTP2Pipeline(
mode: .server,
connectionConfiguration: .init(),
streamConfiguration: .init()
) { streamChannel -> EventLoopFuture<Void> in
streamChannel.pipeline.addHandler(TestServer())
}.wait()
}

measure(identifier: identifier + "_inline_interleaved") {
return try! inlineInterleaved.run()
try! inlineInterleaved.run()
}

inlineInterleaved.tearDown()

var inlineNoninterleaved = try! ServerOnly1KRequestsBenchmark(concurrentStreams: 1) { channel in
_ = try channel.configureHTTP2Pipeline(mode: .server, connectionConfiguration: .init(), streamConfiguration: .init()) { streamChannel -> EventLoopFuture<Void> in
return streamChannel.pipeline.addHandler(TestServer())
_ = try channel.configureHTTP2Pipeline(
mode: .server,
connectionConfiguration: .init(),
streamConfiguration: .init()
) { streamChannel -> EventLoopFuture<Void> in
streamChannel.pipeline.addHandler(TestServer())
}.wait()
}

measure(identifier: identifier + "_inline_noninterleaved") {
return try! inlineNoninterleaved.run()
try! inlineNoninterleaved.run()
}

inlineNoninterleaved.tearDown()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,42 +39,58 @@ final class ServerHandler: ChannelInboundHandler {
}
}


final class ClientHandler: ChannelInboundHandler {
typealias InboundIn = HTTPClientResponsePart
typealias OutboundOut = HTTPClientRequestPart

func channelActive(context: ChannelHandlerContext) {
// Send a request.
let head = HTTPRequestHead(version: .init(major: 2, minor: 0), method: .GET, uri: "/", headers: HTTPHeaders([("host", "localhost")]))
let head = HTTPRequestHead(
version: .init(major: 2, minor: 0),
method: .GET,
uri: "/",
headers: HTTPHeaders([("host", "localhost")])
)
context.write(self.wrapOutboundOut(.head(head)), promise: nil)
context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil)
}
}

func run(identifier: String) {
testRun(identifier: identifier) { clientChannel in
return try! clientChannel.configureHTTP2Pipeline(mode: .client, inboundStreamInitializer: nil).wait()
try! clientChannel.configureHTTP2Pipeline(mode: .client, inboundStreamInitializer: nil).wait()
} serverPipelineConfigurator: { serverChannel in
_ = try! serverChannel.configureHTTP2Pipeline(mode: .server) { channel in
return channel.pipeline.addHandlers([HTTP2FramePayloadToHTTP1ServerCodec(), ServerHandler()])
channel.pipeline.addHandlers([HTTP2FramePayloadToHTTP1ServerCodec(), ServerHandler()])
}.wait()
}

//
// MARK: - Inline HTTP2 multiplexer tests
testRun(identifier: identifier + "_inline") { clientChannel in
return try! clientChannel.configureHTTP2Pipeline(mode: .client, connectionConfiguration: .init(), streamConfiguration: .init()) { channel in
return channel.eventLoop.makeSucceededVoidFuture()
try! clientChannel.configureHTTP2Pipeline(
mode: .client,
connectionConfiguration: .init(),
streamConfiguration: .init()
) { channel in
channel.eventLoop.makeSucceededVoidFuture()
}.wait()
} serverPipelineConfigurator: { serverChannel in
_ = try! serverChannel.configureHTTP2Pipeline(mode: .server, connectionConfiguration: .init(), streamConfiguration: .init()) { channel in
return channel.pipeline.addHandlers([HTTP2FramePayloadToHTTP1ServerCodec(), ServerHandler()])
_ = try! serverChannel.configureHTTP2Pipeline(
mode: .server,
connectionConfiguration: .init(),
streamConfiguration: .init()
) { channel in
channel.pipeline.addHandlers([HTTP2FramePayloadToHTTP1ServerCodec(), ServerHandler()])
}.wait()
}
}

private func testRun(identifier: String, clientPipelineConfigurator: (Channel) throws -> MultiplexerChannelCreator, serverPipelineConfigurator: (Channel) throws -> ()) {
private func testRun(
identifier: String,
clientPipelineConfigurator: (Channel) throws -> MultiplexerChannelCreator,
serverPipelineConfigurator: (Channel) throws -> Void
) {
let loop = EmbeddedEventLoop()

measure(identifier: identifier) {
Expand All @@ -91,7 +107,9 @@ private func testRun(identifier: String, clientPipelineConfigurator: (Channel) t

let promise = clientChannel.eventLoop.makePromise(of: Channel.self)
clientMultiplexer.createStreamChannel(promise: promise) { channel in
return channel.pipeline.addHandlers([HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https), ClientHandler()])
channel.pipeline.addHandlers([
HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https), ClientHandler(),
])
}
clientChannel.embeddedEventLoop.run()
let child = try! promise.futureResult.wait()
Expand All @@ -108,4 +126,3 @@ private func testRun(identifier: String, clientPipelineConfigurator: (Channel) t
return sumOfStreamIDs
}
}

Loading
Loading